package cn.stylefeng.guns.modular.hx.order.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.ListUtil;
import cn.stylefeng.guns.modular.basic.entity.BasicAddress;
import cn.stylefeng.guns.modular.basic.entity.BasicPutgoods;
import cn.stylefeng.guns.modular.basic.service.*;
import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicGoods;
import cn.stylefeng.guns.modular.hx.basic.model.params.HxBasicGoodsParam;
import cn.stylefeng.guns.modular.hx.basic.model.result.HxBasicGoodsResult;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicGoodsService;
import cn.stylefeng.guns.modular.hx.order.entity.TcslOrderPut;
import cn.stylefeng.guns.modular.hx.order.entity.TcslOrderPutDetailed;
import cn.stylefeng.guns.modular.hx.order.service.TcslOrderPutDetailedService;
import cn.stylefeng.guns.modular.hx.order.service.TcslOrderPutService;
import cn.stylefeng.guns.modular.hx.order.utils.EmojiTransferUtil;
import cn.stylefeng.guns.modular.rest.aop.UserAop;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import cn.hutool.http.HttpRequest;
import cn.stylefeng.guns.modular.basic.model.params.BasicXlbOauth2tokenParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicXlbOauth2tokenResult;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.base.shiro.annotion.Permission;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.entity.BasicWarehouse;
import cn.stylefeng.guns.modular.hx.order.entity.HxOrderPut;
import cn.stylefeng.guns.modular.hx.order.entity.HxOrderPutDetailed;
import cn.stylefeng.guns.modular.hx.order.model.params.HxOrderPutDetailedParam;
import cn.stylefeng.guns.modular.hx.order.model.params.HxOrderPutParam;
import cn.stylefeng.guns.modular.hx.order.model.result.HxOrderPutDetailedResult;
import cn.stylefeng.guns.modular.hx.order.model.result.HxOrderPutResult;
import cn.stylefeng.guns.modular.hx.order.service.HxOrderPutDetailedService;
import cn.stylefeng.guns.modular.hx.order.service.HxOrderPutService;
import cn.stylefeng.guns.modular.hx.storage.service.HxStoragePutDetailedService;
import cn.stylefeng.guns.sys.modular.system.entity.Dept;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;


/**
 * 入库订单表控制器
 *
 * @author zhucx
 * @Date 2023-08-05 11:51:01
 */
@Controller
@RequestMapping("/hxOrderPut")
public class HxOrderPutController extends BaseController {

    private String PREFIX = "/hx/order/hxOrderPut";
    @Autowired
    private UserAop userAop;

    @Autowired
    private HxOrderPutService hxOrderPutService;

    @Autowired
    private HxOrderPutDetailedService hxOrderPutDetailedService;

    @Autowired
    private UserService userService;

    @Autowired
    private BasicCustomerService basicCustomerService;

    @Autowired
    private BasicWarehouseService basicWarehouseService;

    @Autowired
    private HxStoragePutDetailedService hxStoragePutDetailedService;
    @Autowired
    private BasicXlbOauth2tokenService basicXlbOauth2tokenService;

    @Autowired
    private HxBasicGoodsService hxBasicGoodsService;

    @Autowired
    private BasicPutgoodsService basicPutgoodsService;
    @Autowired
    private BasicAddressService basicAddressService;

    @Autowired
    private TcslOrderPutService tcslOrderPutService;

    @Autowired
    private TcslOrderPutDetailedService  tcslOrderPutDetailedService;


    private Lock lock = new ReentrantLock();


    /**
     * 导出所有
     */
    @ResponseBody
    @RequestMapping("/listAll")
    public List <HxOrderPutResult> listAll(HxOrderPutParam hxOrderPutParam, String condition, String startTime, String endTime) {
        User user = userService.getcurrentUser();
        hxOrderPutParam.setDeptId(user.getDeptId());
        if (ToolUtil.isEmpty(hxOrderPutParam.getTimeType())) {
            hxOrderPutParam.setTimeType("cj");
        }
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxOrderPutParam.setTimeInterval("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            hxOrderPutParam.setTimeInterval("'" + DateUtil.getDate() + "' and '" + DateUtil.getDate() + "'");
        }
        return this.hxOrderPutService.findlistAllBySpec(hxOrderPutParam, condition, user.getOperateId());
    }

    /**
     * 导出所有
     */
    @ResponseBody
    @RequestMapping("/listAll1")
    public List <HxOrderPutResult> listAll1(HxOrderPutParam hxOrderPutParam, String condition, String startTime, String endTime) {
        User user = userService.getcurrentUser();
        hxOrderPutParam.setDeptId(user.getDeptId());
        if (ToolUtil.isEmpty(hxOrderPutParam.getTimeType())) {
            hxOrderPutParam.setTimeType("cj");
        }
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxOrderPutParam.setTimeInterval("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            hxOrderPutParam.setTimeInterval("'" + DateUtil.getDate() + "' and '" + DateUtil.getDate() + "'");
        }
        return this.hxOrderPutService.listAll1(hxOrderPutParam, condition, user.getOperateId());
    }

    /**
     * 导出所有
     */
    @ResponseBody
    @RequestMapping("/list1")
    public List <HxOrderPutResult> list1(HxOrderPutParam hxOrderPutParam, String condition, String startTime, String endTime) {
        User user = userService.getcurrentUser();
        hxOrderPutParam.setDeptId(user.getDeptId());
        if (ToolUtil.isEmpty(hxOrderPutParam.getTimeType())) {
            hxOrderPutParam.setTimeType("cj");
        }
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxOrderPutParam.setTimeInterval("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            hxOrderPutParam.setTimeInterval("'" + DateUtil.getDate() + "' and '" + DateUtil.getDate() + "'");
        }
        return this.hxOrderPutService.list1(hxOrderPutParam, condition, user.getOperateId());
    }

    /**
     * 导出所有
     */
    @ResponseBody
    @RequestMapping("/List2")
    public List <HxOrderPutResult> List2(HxOrderPutParam hxOrderPutParam, String condition, String startTime, String endTime) {
        User user = userService.getcurrentUser();
        hxOrderPutParam.setDeptId(user.getDeptId());
        if (ToolUtil.isEmpty(hxOrderPutParam.getTimeType())) {
            hxOrderPutParam.setTimeType("cj");
        }
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxOrderPutParam.setTimeInterval("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            hxOrderPutParam.setTimeInterval("'" + DateUtil.getDate() + "' and '" + DateUtil.getDate() + "'");
        }
        return this.hxOrderPutService.List2(hxOrderPutParam, condition, user.getOperateId());
    }

    /**
     * 查询新零帮预约任务
     *
     * @author
     * @Date 2024-04-17
     */
    @RequestMapping("/findPut")
    @ResponseBody
    public ResponseData findPut(String modified_yuyue, Integer customerId, Long setWarehouseId) {
        User user = userService.getcurrentUser();

        BasicCustomer r = basicCustomerService.getById(customerId);

        BasicWarehouse w = basicWarehouseService.getById(setWarehouseId);

        if (ToolUtil.isEmpty(r.getGsnumber())) {
            return ResponseData.error("请维护新零帮公司号");
        }
        if (ToolUtil.isEmpty(r.getStoreIdXlb())) {
            return ResponseData.error("请维护门店id");
        }
        if (ToolUtil.isEmpty(w.getWarehouseXlbId())) {
            return ResponseData.error("请维护新零帮仓库id");
        }
        String url = "https://test-api.xlbsoft.com/api/hxl.open.wms.appointmentorder.findbyupdatetime";
//      String url = "https://hxl-api.xlbsoft.com/api/hxl.open.wms.appointmentorder.findbyupdatetime";

        // 查询预约任务
        JSONObject json = new JSONObject();
        json.put("store_id", r.getStoreIdXlb());
        json.put("storehouse_id", w.getWarehouseXlbId());
        json.put("update_time", modified_yuyue);

//		JSONObject json = new JSONObject();
//		json.put("store_id","100000000005");
//		json.put("storehouse_id", "100000000370");
//		json.put("update_time", modified_yuyue);
        BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
        oauth2tokenParam.setDeliverId(r.getDeliverId());
        oauth2tokenParam.setGsnumber(r.getGsnumber());
        BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);

        String response = HttpRequest.post(url)
                .timeout(60000)
                .header("Company_id", "1000")
                .header("Authorization", "Bearer " + oauth2tokenResult.getOauth2TokenXlb())
                .body(json.toString()).execute().body();
        JSONObject jsonObject = new JSONObject(response);

        if (jsonObject.get("code").toString().equals("0")) {
            JSONArray dataArray = jsonObject.getJSONArray("data");

            // 查回来一个集合，通过遍历集合数据，将数据同步到入库订单表中。
            // 然后通过确认续约任务接口，可以来选择是否确认预约到货

            List <Object> dataList = new ArrayList <>();
            for (int i = 0; i < dataArray.length(); i++) {
                Object item = dataArray.get(i);
                dataList.add(item);
            }

            List <HxOrderPut> hxOrderPutList = new ArrayList();
            List <HxOrderPutDetailed> hxOrderPutDetailedList = new ArrayList();
            for (Object data : dataList) {

                Object id = ((JSONObject) data).get("id");// 主键id
                Object appointTime = ((JSONObject) data).get("appoint_time");// 预约送达时间
                Object contactBy = ((JSONObject) data).get("contact_by");// 联系人
                Object createBy = ((JSONObject) data).get("create_by");// 制单人
                Object createTime = ((JSONObject) data).get("create_time");// 制单时间
                Object itemCount = ((JSONObject) data).get("item_count");// 商品数
                Object operateState = ((JSONObject) data).get("operate_state");// 操作状态 WAITCONFIRM(待确认),WAITSEND(待发号),HASSEND(已发号),FINISH(已结束),可用值:FINISH,HASSEND,WAITCONFIRM,WAITSEND
                Object phone = ((JSONObject) data).get("phone");// 联系方式
                Object plateNumber = ((JSONObject) data).get("plate_number");// 车牌号
                Object quantity = ((JSONObject) data).get("quantity");// 发货数量
                Object storeId = ((JSONObject) data).get("store_id");// 收货门店id

                Object storeName = ((JSONObject) data).get("store_name");// 收货门店名称
                Object storehouseId = ((JSONObject) data).get("storehouse_id");// 收货仓库id

                Object storehouseName = ((JSONObject) data).get("storehouse_name");// 收货仓库名称
                Object supplierId = ((JSONObject) data).get("supplier_id");// 发货供应商id


                Object supplierName = ((JSONObject) data).get("supplier_name");// 发货供应商名称

                Object deliveryOrderCount = ((JSONObject) data).get("delivery_order_count");// 发货单数量
                JSONArray details = ((JSONObject) data).getJSONArray("details");// 明细

                for (Object detail : details) {
                    HxOrderPut hxOrderPutParam = new HxOrderPut();
                    Object detailNum = ((JSONObject) detail).get("detail_num");// 序号
                    Object inApplicationOrderFid = ((JSONObject) detail).get("in_application_order_fid");// 入库申请单单号
                    Object isCarSharing = ((JSONObject) detail).get("is_car_sharing");// 是否拼车
                    Object scmFid = ((JSONObject) detail).get("scm_fid");// 发货单单号
                    Object shippingOrderResDto = ((JSONObject) detail).get("shipping_order_res_dto");
                    if (shippingOrderResDto != null && shippingOrderResDto != JSONObject.NULL) {

                        Object appointState = ((JSONObject) shippingOrderResDto).get("appoint_state");// 预约状态
                        Object appointStateName = ((JSONObject) shippingOrderResDto).get("appoint_state_name");// 预约状态名称
                        Object approveBy = ((JSONObject) shippingOrderResDto).get("approve_by");// 批复人
                        Object approveTime = ((JSONObject) shippingOrderResDto).get("approve_time");// 批复时间
                        Object auditBy = ((JSONObject) shippingOrderResDto).get("audit_by");// 审核人
                        Object auditTime = ((JSONObject) shippingOrderResDto).get("audit_time");// 审核时间
                        Object deliverState = ((JSONObject) shippingOrderResDto).get("deliver_state");// 是否到仓
                        Object deliverStateName = ((JSONObject) shippingOrderResDto).get("deliver_state");// 是否到仓名称
                        Object deliveryDate = ((JSONObject) shippingOrderResDto).get("delivery_date");// 发货日期
                        Object deliveryDeadline = ((JSONObject) shippingOrderResDto).get("delivery_deadline");// 交货期限

                        JSONArray details1 = (JSONArray) ((JSONObject) shippingOrderResDto).get("details");//

                        for (Object details1s : details1) {
                            HxOrderPutDetailed hxOrderPutDetailedParam = new HxOrderPutDetailed();
                            Object basicInPresentQuantity = ((JSONObject) details1s).get("basic_in_present_quantity");//基本入库赠品数量
                            Object basicInQuantity = ((JSONObject) details1s).get("basic_in_quantity");//基本入库数量
                            Object basicPresentQuantity = ((JSONObject) details1s).get("basic_present_quantity");//赠品基本数量
                            Object basicPurchasePrice = ((JSONObject) details1s).get("basic_purchase_price");//订购基本单价
                            Object basicShipQuantity = ((JSONObject) details1s).get("basic_ship_quantity");//发货基本数量
                            Object basicUnit = ((JSONObject) details1s).get("basic_unit");//基本单位
                            Object dateInType = ((JSONObject) details1s).get("date_in_type");//日期录入规则
                            Object deliveryRatio = ((JSONObject) details1s).get("delivery_ratio");//配送单位换算率
                            Object deliveryUnit = ((JSONObject) details1s).get("delivery_unit");//配送单位
                            Object detailNum1 = ((JSONObject) details1s).get("detail_num");//序号
                            Object fid = ((JSONObject) details1s).get("fid");//单据号
                            if (ToolUtil.isNotEmpty(fid) && !fid.equals("null")) {
                                // 校验是否已经添加过
                                Integer count = hxOrderPutDetailedService.lambdaQuery()
                                        .eq(HxOrderPutDetailed::getOrderPutNumber, fid)
                                        .count();
                                if (count > 0) {
                                    break; // 如果数据库中已存在该订单号，则跳过当前循环
                                }
                            }
                            Object imageUrls = ((JSONObject) details1s).get("image_urls");//图片
                            Object inPresentQuantity = ((JSONObject) details1s).get("in_present_quantity");//入库赠品数量
                            Object inQuantity = ((JSONObject) details1s).get("in_quantity");//入库数量
                            Object itemBarCode = ((JSONObject) details1s).get("item_bar_code");//商品条码
                            Object itemCode = ((JSONObject) details1s).get("item_code");//商品代码
                            Object itemId = ((JSONObject) details1s).get("item_id");//商品id
                            Object itemName = ((JSONObject) details1s).get("item_name");//商品名称
                            Object itemSpec = ((JSONObject) details1s).get("item_spec");//商品规格
                            Object memo = ((JSONObject) details1s).get("memo");//
                            Object presentQuantity = ((JSONObject) details1s).get("present_quantity");//赠品数量
                            Object presentRatio = ((JSONObject) details1s).get("present_ratio");//赠品换算率
                            Object presentUnit = ((JSONObject) details1s).get("present_unit");//赠品单位
                            Object purchasePresentQuantity = ((JSONObject) details1s).get("purchase_present_quantity");//订购赠品数量
                            Object purchasePrice = ((JSONObject) details1s).get("purchase_price");//订购单价
                            Object purchaseQuantity = ((JSONObject) details1s).get("purchase_quantity");//订购数量
                            Object purchaseRatio = ((JSONObject) details1s).get("purchase_ratio");//采购单位换算率
                            Object purchaseUnit = ((JSONObject) details1s).get("purchase_unit");//采购单位
                            Object ratio = ((JSONObject) details1s).get("ratio");//换算率
                            Object shipMoney = ((JSONObject) details1s).get("ship_money");//发货金额
                            Object shipPrice = ((JSONObject) details1s).get("ship_price");//发货单价
                            Object shipQuantity = ((JSONObject) details1s).get("ship_quantity");//发货数量
                            Object stockRatio = ((JSONObject) details1s).get("stock_ratio");//库存单位换算率
                            Object stockUnit = ((JSONObject) details1s).get("stock_unit");//库存单位

                            Object unit = ((JSONObject) details1s).get("unit");//单位
                            Object validDays = ((JSONObject) details1s).get("valid_days");//预计可用天数
                            Object volume = ((JSONObject) details1s).get("volume");//体积
                            Object wholesaleRatio = ((JSONObject) details1s).get("wholesale_ratio");//批发单位换算率
                            Object wholesaleUnit = ((JSONObject) details1s).get("wholesale_unit");//批发单位

                            HxBasicGoods goodsid = hxBasicGoodsService.lambdaQuery()
                                    .eq(HxBasicGoods::getGoodsNumber, itemCode)
                                    .select(HxBasicGoods::getId)
                                    .one();
                            if (goodsid == null) {
                                HxBasicGoods hxBasicGoodsParam = new HxBasicGoods();
                                if (ToolUtil.isNotEmpty(itemId.toString()) && !itemId.toString().equals("null")) {
                                    hxBasicGoodsParam.setGoodsXlbId(itemId.toString());
                                }
                                if (ToolUtil.isNotEmpty(itemName.toString()) && !itemName.toString().equals("null")) {
                                    hxBasicGoodsParam.setGoodsName(itemName.toString());
                                }
                                if (ToolUtil.isNotEmpty(itemBarCode.toString()) && !itemBarCode.toString().equals("null")) {
                                    hxBasicGoodsParam.setGoodsPcode69(itemBarCode.toString());
                                }
                                if (ToolUtil.isNotEmpty(itemCode.toString()) && !itemCode.toString().equals("null")) {
                                    hxBasicGoodsParam.setGoodsNumber(itemCode.toString());

                                }
                                if (ToolUtil.isNotEmpty(itemSpec.toString()) && !itemSpec.toString().equals("null")) {
                                    hxBasicGoodsParam.setGoodsSpecs(itemSpec.toString());
                                }
                                if (ToolUtil.isNotEmpty(basicUnit.toString()) && !basicUnit.toString().equals("null")) {
                                    hxBasicGoodsParam.setJibenUnit(basicUnit.toString());
                                }
                                if (ToolUtil.isNotEmpty(stockUnit.toString()) && !stockUnit.toString().equals("null")) {

                                    hxBasicGoodsParam.setKcUnit(stockUnit.toString());
                                }
                                if (ToolUtil.isNotEmpty(stockRatio.toString()) && !stockRatio.toString().equals("null")) {
                                    hxBasicGoodsParam.setKcRate(String.valueOf(stockRatio));
                                }
                                if (ToolUtil.isNotEmpty(purchaseUnit.toString()) && !purchaseUnit.toString().equals("null")) {
                                    hxBasicGoodsParam.setCgUnit(purchaseUnit.toString());
                                }
                                if (ToolUtil.isNotEmpty(purchaseRatio.toString()) && !purchaseRatio.toString().equals("null")) {
                                    hxBasicGoodsParam.setCgRate(String.valueOf(purchaseRatio));
                                }
                                hxBasicGoodsParam.setPfRate(String.valueOf(wholesaleRatio));
                                hxBasicGoodsParam.setPfUnit(wholesaleUnit.toString());
                                hxBasicGoodsParam.setPsRate(String.valueOf(deliveryRatio));
                                hxBasicGoodsParam.setPsUnit(deliveryUnit.toString());
                                hxBasicGoodsParam.setV1(String.valueOf(imageUrls));
                                hxBasicGoodsParam.setCreateTime(new Date());
                                hxBasicGoodsParam.setCreateName(user.getName());
                                hxBasicGoodsParam.setDeliverId(user.getDeliverId());
                                hxBasicGoodsParam.setDeptId(user.getDeptId());
                                hxBasicGoodsParam.setGoodsCustomerName(r.getCustomerName());
                                hxBasicGoodsParam.setGoodsCustomerId(r.getId());
                                hxBasicGoodsParam.setGoodsBottom("10");
                                hxBasicGoodsParam.setGoodsLamination("10");
                                hxBasicGoodsParam.setGoodsTraylayer("1");
                                hxBasicGoodsParam.setGoodsSupportvolume("100");
                                hxBasicGoodsParam.setGoodsChargingCg(String.valueOf(purchasePrice));
                                hxBasicGoodsParam.setGoodsChargingPf(String.valueOf(shipPrice));
                                hxBasicGoodsParam.setGoodsChargingPs("0");
                                hxBasicGoodsParam.setAnquanNum("14");
                                hxBasicGoodsParam.setGoodsWeight("0.1");
                                if (ToolUtil.isNotEmpty(volume.toString()) && !volume.toString().equals("null")) {
                                    hxBasicGoodsParam.setGoodsVolume(volume.toString());
                                } else {
                                    hxBasicGoodsParam.setGoodsVolume("0.1");
                                }
                                hxBasicGoodsParam.setGoodsWarranty("36");
                                hxBasicGoodsService.save(hxBasicGoodsParam);

                                hxOrderPutDetailedParam.setGoodsId(hxBasicGoodsParam.getId().longValue());
                            } else {

                                hxOrderPutDetailedParam.setGoodsId(goodsid.getId().longValue());
                            }

                            hxOrderPutDetailedParam.setOrderPutNumber(String.valueOf(fid));
                            hxOrderPutDetailedParam.setGoodsName(itemName.toString());
                            hxOrderPutDetailedParam.setGoodsSpecs(itemSpec.toString());
                            hxOrderPutDetailedParam.setGoodsPcode69(itemBarCode.toString());
                            hxOrderPutDetailedParam.setGoodsNumber(itemCode.toString());
                            hxOrderPutDetailedParam.setNum(String.valueOf(shipQuantity));
                            hxOrderPutDetailedParam.setUnit(unit.toString());
                            hxOrderPutDetailedParam.setRate(String.valueOf(purchaseRatio));
                            if (ToolUtil.isNotEmpty(volume.toString()) && !volume.toString().equals("null")) {
                                BigDecimal volume1 = new BigDecimal(volume.toString());
                                BigDecimal bigDecimal = new BigDecimal(basicShipQuantity.toString());
                                BigDecimal result = volume1.divide(bigDecimal, 4, RoundingMode.HALF_DOWN);

                                hxOrderPutDetailedParam.setGoodsVolume(result.toString());
                                hxOrderPutDetailedParam.setPutVolume(volume.toString());
                            }
                            hxOrderPutDetailedParam.setZpNum(String.valueOf(presentQuantity));
                            hxOrderPutDetailedParam.setZpRate(String.valueOf(presentRatio));
                            hxOrderPutDetailedParam.setZpUnit(String.valueOf(presentUnit));
                            BigDecimal purchasePrice1 = new BigDecimal(purchaseRatio.toString());
                            BigDecimal bigDecimal = new BigDecimal(basicShipQuantity.toString());
                            BigDecimal bigDecima2 = new BigDecimal(presentQuantity.toString());
                            BigDecimal result = bigDecimal.divide(purchasePrice1, 3, RoundingMode.HALF_DOWN);
                            BigDecimal result1 = bigDecima2.divide(purchasePrice1, 3, RoundingMode.HALF_DOWN);

                            hxOrderPutDetailedParam.setSumNum(String.valueOf(Double.parseDouble(String.valueOf(result1)) + Double.parseDouble(String.valueOf(result))));
                            hxOrderPutDetailedParam.setGoodsPrice(String.valueOf(shipPrice));
                            hxOrderPutDetailedParam.setGoodsSupportvolume("100");
                            hxOrderPutDetailedParam.setGoodsWeight("0.1");

                            hxOrderPutDetailedParam.setXlbOrderPutNumber(String.valueOf(id));

                            hxOrderPutDetailedList.add(hxOrderPutDetailedParam);


                        }
                        this.hxOrderPutDetailedService.saveBatch(hxOrderPutDetailedList);
                        hxOrderPutDetailedList.clear();
                        Object exportAppointTime = ((JSONObject) shippingOrderResDto).get("export_appoint_time");// 预约送达时间
                        Object fid = ((JSONObject) shippingOrderResDto).get("fid");// 单据号
                        Object itemCount1 = ((JSONObject) shippingOrderResDto).get("item_count");// 商品数
                        Object updateTime = ((JSONObject) shippingOrderResDto).get("update_time");// 更新时间
                        hxOrderPutParam.setOrderPutNumber(String.valueOf(fid));
                        if (ToolUtil.isNotEmpty(fid) && !fid.equals("null")) {//单据号
                            // 校验是否已经添加过
                            Integer count = hxOrderPutService.lambdaQuery()
                                    .eq(HxOrderPut::getOrderPutNumber, fid)
                                    .ne(HxOrderPut::getOrderState, "Void")
                                    .count();
                            if (count > 0) {
                                continue; // 如果数据库中已存在该订单号，则跳过当前循环
                            }
                        }

                    }


                    if (ToolUtil.isNotEmpty(appointTime.toString()) && !appointTime.toString().equals("null")) {
                        hxOrderPutParam.setYuyueTime(appointTime.toString());// 预约时间

                    } else {
                        hxOrderPutParam.setYuyueTime(new Date().toString());// 预约时间
                    }

                    BasicPutgoods basicPutgoods = basicPutgoodsService.lambdaQuery()
                            .eq(BasicPutgoods::getXlbClientId, supplierId.toString()).one();

                    BasicWarehouse basicWarehouse = basicWarehouseService.lambdaQuery()
                            .eq(BasicWarehouse::getWarehouseXlbId, storehouseId.toString()).one();


                    if (basicPutgoods == null) {
                        BasicPutgoods bpgp3 = new BasicPutgoods();
                        bpgp3.setPutgoodsCustomerId(r.getId());
                        bpgp3.setPutgoodsOperateName(r.getCustomerName());
                        bpgp3.setPutgoodsName(supplierName.toString());//单位名称
                        bpgp3.setXlbClientId(supplierId.toString());
                        bpgp3.setUnitType("Supplier");
                        bpgp3.setDictId(0l);
                        bpgp3.setDeliverId(user.getDeliverId());
                        bpgp3.setDeptId(user.getDeptId());

                        basicPutgoodsService.save(bpgp3);
                        hxOrderPutParam.setSetUnitId((long) bpgp3.getId());// 发货客户id
                    } else {
                        hxOrderPutParam.setSetUnitId((long) basicPutgoods.getId());// 发货客户id
                    }

                    hxOrderPutParam.setSetUnit(supplierName.toString());//发货客户
                    hxOrderPutParam.setGetWarehouse(storehouseName.toString());// 收货仓库名称
                    hxOrderPutParam.setGetWarehouseId((long) basicWarehouse.getId());//收货仓库id
                    hxOrderPutParam.setGoodsNum(itemCount.toString());//商品数
                    hxOrderPutParam.setContacts(contactBy.toString());//联系人
                    hxOrderPutParam.setTel(String.valueOf(phone));// 联系方式
                    Date date = new Date();
                    hxOrderPutParam.setCreateTime(date);// 创建时间
                    if (operateState.toString().equals("WAITCONFIRM")) {
                        hxOrderPutParam.setOrderState("Pending Confirmation");
                    }
                    if (operateState.toString().equals("WAITSEND")) {
                        continue;
                    }
                    if (operateState.toString().equals("HASSEND")) {
                        continue;
                    }
                    if (operateState.toString().equals("FINISH")) {
                        continue;
                    }    //STORE_IN(门店调入),RECEIVE(采购收货),WHOLESALE_RETURN(批发退货),ADJUST_IN(调整入库),DUMP_IN(甩货入库)，TRANSFER(仓间调拨)
                    if (operateState.toString().equals("STORE_IN")) {

                    }
                    hxOrderPutParam.setOrderType("Purchase Receipt");
                    hxOrderPutParam.setCreateUserName(user.getName());
                    hxOrderPutParam.setXlbOrderId(String.valueOf(id));
                    hxOrderPutParam.setDeptId(user.getDeptId());
                    hxOrderPutParam.setDeliverId(user.getDeliverId());
                    hxOrderPutParam.setCustomerId((long) r.getId());
                    hxOrderPutParam.setCustomerName(r.getCustomerName());
                    hxOrderPutList.add(hxOrderPutParam);

                }
                this.hxOrderPutService.saveBatch(hxOrderPutList);
                hxOrderPutList.clear();
            }


        }
        return ResponseData.success();

    }


    /**
     * 查询新零帮入库申请单
     *
     * @author
     * @Date 2024-04-17
     */
    @RequestMapping("/findPutdetail")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class, timeout = 800000)
    public ResponseData findPutdetail(String modified_begin, String modified_end, Integer customerId, Long setWarehouseId) {
        User user = userService.getcurrentUser();

        BasicCustomer r = basicCustomerService.getById(customerId);

        BasicWarehouse w = basicWarehouseService.getById(setWarehouseId);
        if (ToolUtil.isEmpty(r.getStoreIdXlb())) {
            return ResponseData.error("请维护新零帮发货门店id");
        }
        if (ToolUtil.isEmpty(r.getGsnumber())) {
            return ResponseData.error("请维护新零帮公司号");
        }
        if (ToolUtil.isEmpty(w.getWarehouseXlbId())) {
            return ResponseData.error("请维护新零帮仓库id");
        }
        List <String> update_times = new ArrayList <String>();
        update_times.add(modified_begin);
        update_times.add(modified_end);
        //	String url = "https://test-api.xlbsoft.com/api/hxl.open.wms.inapplicationorder.findbyupdatetime";
        String url = "https://hxl-api.xlbsoft.com/api/hxl.open.wms.inapplicationorder.findbyupdatetime";

        // 查询预约任务
        JSONObject json = new JSONObject();
        json.put("store_id", r.getStoreIdXlb());
        json.put("storehouse_id", w.getWarehouseXlbId());
        json.put("update_times", update_times);

//		JSONObject json = new JSONObject();
//		json.put("store_id","100000000005");
//		json.put("storehouse_id", "100000000370");
//		json.put("update_time", modified_yuyue);
        BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
        oauth2tokenParam.setDeliverId(r.getDeliverId());
        oauth2tokenParam.setGsnumber(r.getGsnumber());
        BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);

        String response = HttpRequest.post(url)
                .header("Authorization", "Bearer " + oauth2tokenResult.getOauth2TokenXlb())
                .body(json.toString()).execute().body();
        JSONObject jsonObject = new JSONObject(response);

        if (jsonObject.get("code").toString().equals("0")) {
            JSONArray dataArray = jsonObject.getJSONArray("data");

            // 查回来一个集合，通过遍历集合数据，将数据同步到入库订单表中。
            // 然后通过确认续约任务接口，可以来选择是否确认预约到货

            List <Object> dataList = new ArrayList <>();
            for (int i = 0; i < dataArray.length(); i++) {
                Object item = dataArray.get(i);
                dataList.add(item);
            }

            List <HxOrderPut> hxOrderPutList = new ArrayList();
            List <HxOrderPutDetailed> hxOrderPutDetailedList = new ArrayList();
            for (Object data : dataList) {
                HxOrderPut hxOrderPutParam = new HxOrderPut();
                Object fid = ((JSONObject) data).get("fid");// 单据号
                Object orderFid = ((JSONObject) data).get("order_fid");// 关联单据号
                Object appointTime = ((JSONObject) data).get("appointment_date");// 预约送达时间
                Object createBy = ((JSONObject) data).get("create_by");// 制单人
                Object createTime = ((JSONObject) data).get("create_time");// 制单时间
                Object itemCount = ((JSONObject) data).get("item_count");// 商品数
                Object quantity = ((JSONObject) data).get("quantity");// 发货数量
                Object storeId = ((JSONObject) data).get("store_id");// 收货门店id
                Object storeName = ((JSONObject) data).get("store_name");// 收货门店名称
                Object storehouseId = ((JSONObject) data).get("storehouse_id");// 收货仓库id
                Object storehouseName = ((JSONObject) data).get("storehouse_name");// 收货仓库名称
                Object clientId = ((JSONObject) data).get("client_id");// 发货供应商id
                Object clientName = ((JSONObject) data).get("client_name");// 发货供应商名称
                Object orderType = ((JSONObject) data).get("order_type");// 单据类型
                Object meno = ((JSONObject) data).get("memo");// 单据类型

                JSONArray details = ((JSONObject) data).getJSONArray("details");// 明细


                for (Object details1s : details) {
                    HxOrderPutDetailed hxOrderPutDetailedParam = new HxOrderPutDetailed();
                    Object basicUnit = ((JSONObject) details1s).get("basic_unit");//基本单位

                    Object basicVolume = ((JSONObject) details1s).get("basic_volume");//基本单位体积

                    Object categoryId = ((JSONObject) details1s).get("category_id");//商品分类id
                    Object categoryName = ((JSONObject) details1s).get("category_name");//商品分类名称


                    Object dateInType = ((JSONObject) details1s).get("date_in_type");//日期录入规则
                    Object deliveryRatio = ((JSONObject) details1s).get("delivery_ratio");//配送单位换算率
                    Object deliveryUnit = ((JSONObject) details1s).get("delivery_unit");//配送单位
                    Object presentInQuantity = ((JSONObject) details1s).get("present_in_quantity");//实收赠品数量
                    Object presentQuantity = ((JSONObject) details1s).get("present_quantity");//申请赠品数量
                    Object presentRatio = ((JSONObject) details1s).get("present_ratio");//赠品换算率
                    Object presentUnit = ((JSONObject) details1s).get("present_unit");//赠品单位
                    Object presentVolume = ((JSONObject) details1s).get("present_volume");//赠品体积
                    Object inQuantity = ((JSONObject) details1s).get("in_quantity");//入库数量
                    Object purchaseRatio = ((JSONObject) details1s).get("purchase_ratio");//采购单位换算率
                    Object purchaseUnit = ((JSONObject) details1s).get("purchase_unit");//采购单位
                    Object quantity1 = ((JSONObject) details1s).get("quantity");//申请数量
                    Object unit = ((JSONObject) details1s).get("unit");//单位
                    Object ratio = ((JSONObject) details1s).get("ratio");//换算率
                    Object volume = ((JSONObject) details1s).get("volume");//体积
                    Object wholesaleRatio = ((JSONObject) details1s).get("wholesale_ratio");//批发单位换算率
                    Object wholesaleUnit = ((JSONObject) details1s).get("wholesale_unit");//批发单位
                    Object stockRatio = ((JSONObject) details1s).get("stock_ratio");//库存单位换算率
                    Object stockUnit = ((JSONObject) details1s).get("stock_unit");//库存单位

                    Object itemBarCode = ((JSONObject) details1s).get("item_bar_code");//商品条码
                    Object itemCode = ((JSONObject) details1s).get("item_code");//商品代码
                    Object itemId = ((JSONObject) details1s).get("item_id");//商品id
                    Object itemName = ((JSONObject) details1s).get("item_name");//商品名称
                    Object itemSpec = ((JSONObject) details1s).get("item_spec");//商品规格
                    Object memo = ((JSONObject) details1s).get("memo");//备注
                    HxBasicGoodsParam hxBasicGoodsParamS = new HxBasicGoodsParam();
                    hxBasicGoodsParamS.setGoodsXlbId(itemId.toString());
                    hxBasicGoodsParamS.setGoodsCustomerId(r.getId());

                    HxBasicGoodsResult goodsid = hxBasicGoodsService.findBySpec(hxBasicGoodsParamS, user.getOperateId());
//					HxBasicGoods goodsid = hxBasicGoodsService.lambdaQuery()
//									.eq(HxBasicGoods::getGoodsXlbId, itemId)
//									.one();
                    if (goodsid == null) {
                        HxBasicGoods hxBasicGoodsParam = new HxBasicGoods();
                        if (ToolUtil.isNotEmpty(itemId.toString()) && !itemId.toString().equals("null")) {
                            hxBasicGoodsParam.setGoodsXlbId(itemId.toString());
                        }
                        if (ToolUtil.isNotEmpty(itemName.toString()) && !itemName.toString().equals("null")) {
                            hxBasicGoodsParam.setGoodsName(itemName.toString());
                        }
                        if (ToolUtil.isNotEmpty(itemBarCode.toString()) && !itemBarCode.toString().equals("null")) {
                            hxBasicGoodsParam.setGoodsPcode69(itemBarCode.toString());
                        }
                        if (ToolUtil.isNotEmpty(itemCode.toString()) && !itemCode.toString().equals("null")) {
                            hxBasicGoodsParam.setGoodsNumber(itemCode.toString());

                        }
                        if (ToolUtil.isNotEmpty(itemSpec.toString()) && !itemSpec.toString().equals("null")) {
                            hxBasicGoodsParam.setGoodsSpecs(itemSpec.toString());
                        }
                        if (ToolUtil.isNotEmpty(basicUnit.toString()) && !basicUnit.toString().equals("null")) {
                            hxBasicGoodsParam.setJibenUnit(basicUnit.toString());
                        }
                        if (ToolUtil.isNotEmpty(stockUnit.toString()) && !stockUnit.toString().equals("null")) {

                            hxBasicGoodsParam.setKcUnit(stockUnit.toString());
                        }
                        if (ToolUtil.isNotEmpty(stockRatio.toString()) && !stockRatio.toString().equals("null")) {
                            hxBasicGoodsParam.setKcRate(String.valueOf(stockRatio));
                        }
                        if (ToolUtil.isNotEmpty(purchaseUnit.toString()) && !purchaseUnit.toString().equals("null")) {
                            hxBasicGoodsParam.setCgUnit(purchaseUnit.toString());
                        }
                        if (ToolUtil.isNotEmpty(purchaseRatio.toString()) && !purchaseRatio.toString().equals("null")) {
                            hxBasicGoodsParam.setCgRate(String.valueOf(purchaseRatio));
                        }else {
                            hxBasicGoodsParam.setCgRate(ratio.toString());
                        }
                        hxBasicGoodsParam.setPfRate(String.valueOf(wholesaleRatio));
                        hxBasicGoodsParam.setPfUnit(wholesaleUnit.toString());
                        hxBasicGoodsParam.setPsRate(String.valueOf(deliveryRatio));
                        hxBasicGoodsParam.setPsUnit(deliveryUnit.toString());
                        hxBasicGoodsParam.setCreateTime(new Date());
                        hxBasicGoodsParam.setCreateName(user.getName());
                        hxBasicGoodsParam.setDeliverId(user.getDeliverId());
                        hxBasicGoodsParam.setDeptId(user.getDeptId());
                        hxBasicGoodsParam.setGoodsCustomerName(r.getCustomerName());
                        hxBasicGoodsParam.setGoodsCustomerId(r.getId());
                        hxBasicGoodsParam.setGoodsBottom("10");
                        hxBasicGoodsParam.setGoodsLamination("10");
                        hxBasicGoodsParam.setGoodsTraylayer("1");
                        hxBasicGoodsParam.setGoodsSupportvolume("100");
                        hxBasicGoodsParam.setAnquanNum("14");

                        hxBasicGoodsParam.setGoodsChargingCg("10");
                        hxBasicGoodsParam.setGoodsChargingPf("10");
                        hxBasicGoodsParam.setGoodsChargingPs("10");
                        hxBasicGoodsParam.setGoodsVolume("0.015");
                        hxBasicGoodsParam.setGoodsWeight("0.015");

                        if (purchaseRatio.toString().equals(deliveryRatio.toString())) {
                            hxBasicGoodsParam.setDismantlingParts("No");
                        } else {
                            hxBasicGoodsParam.setDismantlingParts("Yes");
                        }

                        hxBasicGoodsParam.setGoodsBigtypedictId((long) categoryId);
                        hxBasicGoodsParam.setGoodsBigtype(categoryName.toString());
                        BigDecimal decimal = new BigDecimal(purchaseRatio.toString());
                        BigDecimal bigDecimal = new BigDecimal(quantity1.toString());
                        BigDecimal ratio1 = new BigDecimal(ratio.toString());
                        BigDecimal multiply = ratio1.multiply(bigDecimal);
                        BigDecimal divide = multiply.divide(decimal, 4, RoundingMode.HALF_DOWN);

                        BigDecimal bigDecima2 = new BigDecimal(presentQuantity.toString());

                        BigDecimal decimal1 = new BigDecimal(presentRatio.toString());
                        BigDecimal multiply1 = ratio1.multiply(bigDecima2);
                        BigDecimal divide1 = multiply1.divide(decimal, 4, RoundingMode.HALF_DOWN);
                        Double sumNum = Double.parseDouble(String.valueOf(divide)) + Double.parseDouble(String.valueOf(divide1));


                        if (ToolUtil.isNotEmpty(volume.toString()) && !volume.toString().equals("null")) {
                            BigDecimal v = new BigDecimal(volume.toString());
                            BigDecimal b = new BigDecimal(sumNum.toString());

                            BigDecimal result = v.divide(b, 4, RoundingMode.HALF_DOWN);
                            if (result.compareTo(new BigDecimal("1")) > 0) {
                                hxBasicGoodsParam.setGoodsVolume("0.015");
                            } else {
                                hxBasicGoodsParam.setGoodsVolume(result.toString());
                            }
                        } else {
                            hxBasicGoodsParam.setGoodsVolume("0.015");
                        }
                        hxBasicGoodsParam.setGoodsWarranty("36");
                        hxBasicGoodsService.save(hxBasicGoodsParam);
                        goodsid = new HxBasicGoodsResult();
                        ToolUtil.copyProperties(goodsid, hxBasicGoodsParam);
//								HxBasicGoodsParam hxBasicGoodsParam1 = new HxBasicGoodsParam();
//								hxBasicGoodsParam1.setGoodsXlbId(itemId.toString());
//								hxBasicGoodsParam1.setGoodsCustomerId(r.getId());
//					      HxBasicGoodsResult goodsResult = hxBasicGoodsService.findBySpec(hxBasicGoodsParam1, user.getOperateId());
//
//					    hxOrderPutDetailedParam.setGoodsId(goodsResult.getId().longValue());
                        hxOrderPutDetailedParam.setGoodsId(hxBasicGoodsParam.getId().longValue());

                    } else {

                        hxOrderPutDetailedParam.setGoodsId(goodsid.getId().longValue());
                    }

                    hxOrderPutDetailedParam.setOrderPutNumber(String.valueOf(fid));
                    hxOrderPutDetailedParam.setGoodsName(itemName.toString());
                    hxOrderPutDetailedParam.setGoodsSpecs(itemSpec.toString());
                    hxOrderPutDetailedParam.setGoodsPcode69(itemBarCode.toString());
                    hxOrderPutDetailedParam.setGoodsNumber(itemCode.toString());
                    hxOrderPutDetailedParam.setUnit(unit.toString());
                    hxOrderPutDetailedParam.setRate(String.valueOf(purchaseRatio));
                    if (ToolUtil.isNotEmpty(memo.toString()) && !memo.toString().equals("null")) {
                        hxOrderPutDetailedParam.setNotes(memo.toString());

                    }



                    BigDecimal decimal = new BigDecimal(purchaseRatio.toString());
                    BigDecimal bigDecimal = new BigDecimal(quantity1.toString());
                    BigDecimal ratio1 = new BigDecimal(ratio.toString());
                    BigDecimal multiply = ratio1.multiply(bigDecimal);
                    BigDecimal divide = multiply.divide(decimal, 4, RoundingMode.HALF_DOWN);

                    BigDecimal bigDecima2 = new BigDecimal(presentQuantity.toString());

                    BigDecimal decimal1 = new BigDecimal(presentRatio.toString());
                    BigDecimal multiply1 = ratio1.multiply(bigDecima2);
                    BigDecimal divide1 = multiply1.divide(decimal, 4, RoundingMode.HALF_DOWN);
                    Double sumNum = Double.parseDouble(String.valueOf(divide)) + Double.parseDouble(String.valueOf(divide1));
                    hxOrderPutDetailedParam.setSumNum(String.valueOf(sumNum));
                    Double jibenNumSum = Double.parseDouble(String.valueOf(multiply)) + Double.parseDouble(String.valueOf(multiply1));

                    hxOrderPutDetailedParam.setJibenNum(jibenNumSum.toString());
                    hxOrderPutDetailedParam.setJibenUnit(basicUnit.toString());
                    if (ToolUtil.isNotEmpty(volume) && !volume.toString().equals("null")) {
                        if (goodsid != null && ToolUtil.isNotEmpty(goodsid.getGoodsVolume()) && !"null".equals(goodsid.getGoodsVolume())) {
                            BigDecimal nums11 = new BigDecimal(goodsid.getGoodsVolume());
                            BigDecimal multiply2 = nums11.multiply(new BigDecimal(sumNum.toString()));
                            hxOrderPutDetailedParam.setGoodsVolume(goodsid.getGoodsVolume());
                            hxOrderPutDetailedParam.setPutVolume(multiply2.toString());
                        } else {
                            BigDecimal nums11 = new BigDecimal("0.01");
                            BigDecimal multiply2 = nums11.multiply(new BigDecimal(sumNum.toString()));
                            hxOrderPutDetailedParam.setGoodsVolume(nums11.toString());
                            hxOrderPutDetailedParam.setPutVolume(multiply2.toString());
                        }

                    }
                    hxOrderPutDetailedParam.setNum(String.valueOf(divide));
                    hxOrderPutDetailedParam.setZpNum(String.valueOf(divide1));
                    hxOrderPutDetailedParam.setZpRate(String.valueOf(presentRatio));
                    hxOrderPutDetailedParam.setZpUnit(String.valueOf(presentUnit));
                    hxOrderPutDetailedParam.setZpJibenNum(divide1.multiply(new BigDecimal(presentRatio.toString())).toString());

                    if(ToolUtil.isNotEmpty(goodsid.getGoodsSupportvolume())){
                        hxOrderPutDetailedParam.setGoodsSupportvolume(goodsid.getGoodsSupportvolume());
                    }else {
                        hxOrderPutDetailedParam.setGoodsSupportvolume("100");
                    }

                    if(ToolUtil.isNotEmpty(goodsid.getGoodsWeight())){
                        hxOrderPutDetailedParam.setGoodsWeight(goodsid.getGoodsWeight());
                    }else {
                        hxOrderPutDetailedParam.setGoodsWeight("0.015");
                    }
                    BigDecimal numsweight = new BigDecimal(0);
                    if(ToolUtil.isNotEmpty(goodsid.getGoodsWeight())){
                        numsweight = new BigDecimal(goodsid.getGoodsWeight());
                    }
                    BigDecimal multiply4 = numsweight.multiply(new BigDecimal(sumNum.toString()));

                    hxOrderPutDetailedParam.setPutWeight(String.valueOf(multiply4));
                    BigDecimal cgPrice = new BigDecimal(10);
                    if(ToolUtil.isNotEmpty(goodsid.getGoodsChargingCg())){
                        cgPrice = new BigDecimal(goodsid.getGoodsChargingCg());
                    }

                    BigDecimal result = cgPrice.multiply(new BigDecimal(sumNum)).multiply(new BigDecimal(purchaseRatio.toString()));
                    hxOrderPutDetailedParam.setPutMoney(result.toString());
                    BigDecimal result1 = cgPrice.multiply(new BigDecimal(purchaseRatio.toString()));

                    hxOrderPutDetailedParam.setGoodsPrice(result1.toString());

                    hxOrderPutDetailedParam.setUnitType("Purchase Unit");
                    hxOrderPutDetailedParam.setXlbOrderPutNumber(String.valueOf(orderFid));
                    if (ToolUtil.isNotEmpty(goodsid.getDismantlingParts())) {
                        hxOrderPutDetailedParam.setDismantlingParts(goodsid.getDismantlingParts());
                    }else{
                        if (purchaseRatio.toString().equals(deliveryRatio.toString())) {
                            hxOrderPutDetailedParam.setDismantlingParts("No");
                        } else {
                            hxOrderPutDetailedParam.setDismantlingParts("Yes");
                        }
                    }

                    if (ToolUtil.isNotEmpty(fid) && !fid.equals("null")) {//单据号
                        // 校验是否已经添加过
                        Integer count = hxOrderPutDetailedService.lambdaQuery()
                                .eq(HxOrderPutDetailed::getOrderPutNumber, fid)
                                .count();
                        if (count == (int) itemCount) {
                            continue; // 如果数据库中已存在该订单号，则跳过当前循环
                        }
                    }
                    hxOrderPutDetailedList.add(hxOrderPutDetailedParam);


                    this.hxOrderPutDetailedService.saveBatch(hxOrderPutDetailedList);
                    hxOrderPutDetailedList.clear();

                }

                if (ToolUtil.isNotEmpty(fid) && !fid.equals("null")) {//单据号
                    // 校验是否已经添加过
                    Integer count = hxOrderPutService.lambdaQuery()
                            .eq(HxOrderPut::getOrderPutNumber, fid)
                            .ne(HxOrderPut::getOrderState, "作废")
                            .count();
                    if (count > 0) {
                        continue; // 如果数据库中已存在该订单号，则跳过当前循环
                    }
                }


                hxOrderPutParam.setOrderPutNumber(String.valueOf(fid));
                Date date = new Date();
                if (ToolUtil.isNotEmpty(appointTime.toString()) && !appointTime.toString().equals("null")) {
                    hxOrderPutParam.setYuyueTime(appointTime.toString());// 预约时间
                } else {

                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String dateString = dateFormat.format(date);
                    hxOrderPutParam.setYuyueTime(dateString);// 预约时间
                }
                BasicPutgoods basicPutgoods = basicPutgoodsService.lambdaQuery()
                        .eq(BasicPutgoods::getPutgoodsCustomerId, r.getId())
                        .eq(BasicPutgoods::getXlbClientId, clientId.toString())
                        .eq(BasicPutgoods::getPutgoodsName, clientName.toString())
                        .last("limit 1")
                        .one();

                if (basicPutgoods == null) {
                    BasicPutgoods bpgp3 = new BasicPutgoods();
                    bpgp3.setPutgoodsCustomerId(r.getId());
                    bpgp3.setPutgoodsOperateName(r.getCustomerName());
                    bpgp3.setPutgoodsName(clientName.toString());//单位名称
                    bpgp3.setPutgoodsAddress(clientName.toString());
                    bpgp3.setXlbClientId(clientId.toString());
                    bpgp3.setUnitType("供应商");
                    bpgp3.setDictId(0l);
                    bpgp3.setDeliverId(user.getDeliverId());
                    bpgp3.setDeptId(user.getDeptId());

                    basicPutgoodsService.save(bpgp3);

                    BasicAddress bap3 = new BasicAddress();
                    bap3.setPutgoodsId(Long.parseLong(bpgp3.getId().toString()));
                    bap3.setPutgoodsName(clientName.toString());//单位名称
                    bap3.setAddress(clientName.toString());//地点 为单位名称
                    bap3.setLongitude("0");
                    bap3.setLatitude("0");
                    bap3.setSwitchWl("1");
                    bap3.setSwitchBj("1500");//提货围栏半径 默认100米
                    bap3.setSwitchBj2("2000");//收货围栏半径 默认100米
                    basicAddressService.save(bap3);

                    hxOrderPutParam.setSetUnitId((long) bpgp3.getId());// 发货客户id
                } else {
                    hxOrderPutParam.setSetUnitId((long) basicPutgoods.getId());// 发货客户id
                }

                hxOrderPutParam.setSetUnit(clientName.toString());//发货客户
                hxOrderPutParam.setGetWarehouse(storehouseName.toString());// 收货仓库名称
                hxOrderPutParam.setGetWarehouseId(setWarehouseId);//收货仓库id
                hxOrderPutParam.setGoodsNum(itemCount.toString());//商品数


                hxOrderPutParam.setCreateTime(date);// 创建时间

                if (orderType.toString().equals("RECEIVE")) {
                    hxOrderPutParam.setOrderType("Purchase Receipt");
                }
                if (orderType.toString().equals("STORE_IN")) {
                    hxOrderPutParam.setOrderType("Store Transfer In");
                }
                if (orderType.toString().equals("WHOLESALE_RETURN")) {
                    hxOrderPutParam.setOrderType("Wholesale Return");
                }
                if (orderType.toString().equals("ADJUST_IN")) {
                    hxOrderPutParam.setOrderType("Adjustment Storage");
                }
                if (orderType.toString().equals("DUMP_IN")) {
                    hxOrderPutParam.setOrderType("Clearance Storage");
                }
                if (orderType.toString().equals("TRANSFER")) {
                    hxOrderPutParam.setOrderType("Warehouse Transfer");
                }
                hxOrderPutParam.setOrderState("Pending Submission");
                hxOrderPutParam.setNotes(meno.toString());// 备注

                hxOrderPutParam.setCreateUserName(user.getName());
                hxOrderPutParam.setXlbOrderId(String.valueOf(orderFid));
                hxOrderPutParam.setDeptId(user.getDeptId());
                hxOrderPutParam.setDeliverId(user.getDeliverId());
                hxOrderPutParam.setCustomerId((long) r.getId());
                hxOrderPutParam.setCustomerName(r.getCustomerName());
                hxOrderPutList.add(hxOrderPutParam);

            }
            this.hxOrderPutService.saveBatch(hxOrderPutList);
            hxOrderPutList.clear();
        }

        return ResponseData.success();

    }


    /**
     * 跳转到拉取新零帮预约任务页面
     *
     * @author zhucx
     * @Date 2023-08-05
     */
    @RequestMapping("xlbYuyue")
    public String toxlbYuyue(Model model) {

        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId, deliverId, user.getOperateId()));
        model.addAttribute("wlist", basicWarehouseService.findAvailableList(deptId, deliverId, user.getOperateId()));

        return PREFIX + "/xlbYuyue.html";
    }

    /**
     * 查询tcsl入库申请单
     */
    @RequestMapping("/findTcslPutdetail")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class, timeout = 800000)
    public ResponseData findTcslPutdetail(String modified_begin, String modified_end, Integer customerId, Long setWarehouseId) {
        User user = userService.getcurrentUser();

        BasicCustomer r = basicCustomerService.getById(customerId);

        BasicWarehouse w = basicWarehouseService.getById(setWarehouseId);
//        w.setWarehouseXlbId("6666600000775");

//        if (ToolUtil.isEmpty(r.getStoreIdXlb())) {
//            return ResponseData.error("请维护天财商龙发货门店id");
//        }
//        if (ToolUtil.isEmpty(r.getGsnumber())) {
//            return ResponseData.error("请维护天财商龙公司号");
//        }
//        if (ToolUtil.isEmpty(w.getWarehouseXlbId())) {
//            return ResponseData.error("请维护天财商龙仓库id");
//        }
        List<String> update_times = new ArrayList<String>();
        update_times.add(modified_begin);
        update_times.add(modified_end);
        // tcsl API地址
        String url = "https://tcsl.engine.fxscm.net/business/standard/api/v1/bill/in_store";

        //品项单位接口  API地址
        String itemUnitUrl = "https://tcsl.engine.fxscm.net/business/standard/api/v1/item_unit";

        //品项档案接口  API地址
        String itemUrl = "https://tcsl.engine.fxscm.net/business/standard/api/v1/item";

        // 查询预约任务
        JSONObject json = new JSONObject();
        json.put("entCode", "ENT136140");
        json.put("beginDate", modified_begin);
        json.put("endDate", modified_end);
        if(ToolUtil.isNotEmpty(r.getStoreIdXlb())){
            json.put("organId", ListUtil.of(r.getStoreIdXlb().split(",")));
        }
        json.put("billState", "2");

        String response = HttpRequest.post(url)
                .body(json.toString()).execute().body();

        String responseItemUnit = HttpRequest.post(itemUnitUrl)
                .body(json.toString())
                .execute().body();

        String responseItem = HttpRequest.post(itemUrl)
                .body(json.toString())
                .execute().body();

        JSONObject jsonObject = new JSONObject(response);
        JSONObject jsonItemUnitObject = new JSONObject(responseItemUnit);
        JSONObject jsonItemObject = new JSONObject(responseItem);


        if (jsonObject.get("code").toString().equals("0")) {
            JSONArray dataArray = jsonObject.getJSONArray("data");

            List<Object> dataList = new ArrayList<>();
            for (int i = 0; i < dataArray.length(); i++) {
                Object item = dataArray.get(i);
                dataList.add(item);
            }

            List<HxOrderPut> hxOrderPutList = new ArrayList();
            List<HxOrderPutDetailed> hxOrderPutDetailedList = new ArrayList();
            for (Object data : dataList) {
                HxOrderPut hxOrderPutParam = new HxOrderPut();

                Object id = ((JSONObject) data).opt("id");// 入库单主键Id
                Object billType = ((JSONObject) data).opt("billType");// 单据类型
                Object billTypeName = ((JSONObject) data).opt("billTypeName");// 单据类型名称
                Object billBizTypeId = ((JSONObject) data).opt("billBizTypeId");// 单据业务类型ID
                Object billBizTypeName = ((JSONObject) data).opt("billBizTypeName");// 单据业务类型名称
                Object autoType = ((JSONObject) data).opt("autoType");// 单据自动生成标记
                Object sysBillCode = ((JSONObject) data).opt("sysBillCode");// 单据系统编号
                Object balanceFlag = ((JSONObject) data).opt("balanceFlag");// 结转标志
                Object userBillCode = ((JSONObject) data).opt("userBillCode");// 单据手工编号
                Object businessDate = ((JSONObject) data).opt("businessDate");// 入库时间
                Object checkDate = ((JSONObject) data).opt("checkDate");// 审核时间
                Object createDate = ((JSONObject) data).opt("createDate");// 制单时间
                Object organId = ((JSONObject) data).opt("organId");// 入库机构ID
                Object organName = ((JSONObject) data).opt("organName");// 入库机构名称
                Object organCode = ((JSONObject) data).opt("organCode");// 入库机构编号
                Object organType = ((JSONObject) data).opt("organType");// 入库机构类型
                Object otherOrganId = ((JSONObject) data).opt("otherOrganId");// 出库机构ID
                Object otherOrganName = ((JSONObject) data).opt("otherOrganName");// 出库机构名称
                Object otherOrganCode = ((JSONObject) data).opt("otherOrganCode");// 出库机构编号
                Object otherOrganType = ((JSONObject) data).opt("otherOrganType");// 对方机构类型
                Object recheckState = ((JSONObject) data).opt("recheckState");// 复审标记
                Object memo = ((JSONObject) data).opt("memo");// 整单备注
                Object sumMoney = ((JSONObject) data).opt("sumMoney");// 入库非税总金额
                Object sumTaxMoney = ((JSONObject) data).opt("sumTaxMoney");// 入库含税总金额
                Object sumCarriageFee = ((JSONObject) data).opt("sumCarriageFee");// 整单运费
                Object isPrint = ((JSONObject) data).opt("isPrint");// 是否打印
                Object sendState = ((JSONObject) data).opt("sendState");// 发单状态
                Object operateManId = ((JSONObject) data).opt("operateManId");// 经办人id
                Object operateManCode = ((JSONObject) data).opt("operateManCode");// 经办人编号
                Object operateManName = ((JSONObject) data).opt("operateManName");// 经办人名称
                Object createManId = ((JSONObject) data).opt("createManId");// 制单人id
                Object inCreateManName = ((JSONObject) data).opt("inCreateManName");// 制单人名称
                Object logisticsId = ((JSONObject) data).opt("logisticsId");// 物流公司id
                Object logisticsName = ((JSONObject) data).opt("logisticsName");// 物流公司名称
                Object parentBillCode = ((JSONObject) data).opt("parentBillCode");// 上级单据单号
                Object tradeOrganClassCode = ((JSONObject) data).opt("tradeOrganClassCode");// 营业门店编码
                Object tradeOrganClassName = ((JSONObject) data).opt("tradeOrganClassName");// 营业门店名称
                Object tradeOrganClassCode2 = ((JSONObject) data).opt("tradeOrganClassCode2");// 对方机构-营业门店编码
                Object tradeOrganClassName2 = ((JSONObject) data).opt("tradeOrganClassName2");// 对方机构-营业门店名称
                JSONArray details = ((JSONObject) data).getJSONArray("details");// 明细

                // 创建tcsl_order_put主表对象
                TcslOrderPut tcslOrderPut = new TcslOrderPut();
                tcslOrderPut.setId(id != null ? id.toString() : null);
                tcslOrderPut.setBillType(billType != null ? billType.toString() : null);
                tcslOrderPut.setBillTypeName(billTypeName != null ? billTypeName.toString() : null);
                tcslOrderPut.setBillBizTypeId(billBizTypeId != null ? billBizTypeId.toString() : null);
                tcslOrderPut.setBillBizTypeName(billBizTypeName != null ? billBizTypeName.toString() : null);
                tcslOrderPut.setAutoType(autoType != null ? autoType.toString() : null);
                tcslOrderPut.setSysBillCode(sysBillCode != null ? sysBillCode.toString() : null);
                tcslOrderPut.setBalanceFlag(balanceFlag != null ? balanceFlag.toString() : null);
                tcslOrderPut.setUserBillCode(userBillCode != null ? userBillCode.toString() : null);
//                tcslOrderPut.setBusinessDate(businessDate != null ? DateUtils.parseDate(businessDate.toString()) : null);
//                tcslOrderPut.setCheckDate(checkDate != null ? DateUtils.parseDate(checkDate.toString()) : null);
//                tcslOrderPut.setCreateDate(createDate != null ? DateUtils.parseDate(createDate.toString()) : null);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    if (businessDate != null && !businessDate.toString().equals("null") && !businessDate.toString().isEmpty()) {
                        tcslOrderPut.setBusinessDate(sdf.parse(businessDate.toString()));
                    }
                    if (checkDate != null && !checkDate.toString().equals("null") && !checkDate.toString().isEmpty()) {
                        tcslOrderPut.setCheckDate(sdf.parse(checkDate.toString()));
                    }
                    if (createDate != null && !createDate.toString().equals("null") && !createDate.toString().isEmpty()) {
                        tcslOrderPut.setCreateDate(sdf.parse(createDate.toString()));
                    }
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }

                tcslOrderPut.setOrganId(organId != null ? organId.toString() : null);
                tcslOrderPut.setOrganName(organName != null ? organName.toString() : null);
                tcslOrderPut.setOrganCode(organCode != null ? organCode.toString() : null);
                tcslOrderPut.setOrganType(organType != null ? organType.toString() : null);
                tcslOrderPut.setOtherOrganId(otherOrganId != null ? otherOrganId.toString() : null);
                tcslOrderPut.setOtherOrganName(otherOrganName != null ? otherOrganName.toString() : null);
                tcslOrderPut.setOtherOrganCode(otherOrganCode != null ? otherOrganCode.toString() : null);
                tcslOrderPut.setOtherOrganType(otherOrganType != null ? otherOrganType.toString() : null);
                tcslOrderPut.setRecheckState(recheckState != null ? recheckState.toString() : null);
                tcslOrderPut.setMemo(memo != null ? memo.toString() : null);
                tcslOrderPut.setSumMoney(sumMoney != null ? new BigDecimal(sumMoney.toString()) : null);
                tcslOrderPut.setSumTaxMoney(sumTaxMoney != null ? new BigDecimal(sumTaxMoney.toString()) : null);
                tcslOrderPut.setSumCarriageFee(sumCarriageFee != null ? new BigDecimal(sumCarriageFee.toString()) : null);
                tcslOrderPut.setIsPrint(isPrint != null ? isPrint.toString() : null);
                tcslOrderPut.setSendState(sendState != null ? sendState.toString() : null);
                tcslOrderPut.setOperateManId(operateManId != null ? operateManId.toString() : null);
                tcslOrderPut.setOperateManCode(operateManCode != null ? operateManCode.toString() : null);
                tcslOrderPut.setOperateManName(operateManName != null ? operateManName.toString() : null);
                tcslOrderPut.setCreateManId(createManId != null ? createManId.toString() : null);
                tcslOrderPut.setInCreateManName(inCreateManName != null ? inCreateManName.toString() : null);
                tcslOrderPut.setLogisticsId(logisticsId != null ? logisticsId.toString() : null);
                tcslOrderPut.setLogisticsName(logisticsName != null ? logisticsName.toString() : null);
                tcslOrderPut.setParentBillCode(parentBillCode != null ? parentBillCode.toString() : null);
                tcslOrderPut.setTradeOrganClassCode(tradeOrganClassCode != null ? tradeOrganClassCode.toString() : null);
                tcslOrderPut.setTradeOrganClassName(tradeOrganClassName != null ? tradeOrganClassName.toString() : null);
                tcslOrderPut.setTradeOrganClassCode2(tradeOrganClassCode2 != null ? tradeOrganClassCode2.toString() : null);
                tcslOrderPut.setTradeOrganClassName2(tradeOrganClassName2 != null ? tradeOrganClassName2.toString() : null);

                // 保存主表数据
                tcslOrderPutService.save(tcslOrderPut);

                List<TcslOrderPutDetailed> tcslOrderPutDetailedList = new ArrayList<>();

                int goodsCount = 0;

                for (Object details1s : details) {
                    //限制仓库
                    Object inHouseId = ((JSONObject) details1s).opt("inHouseId");//出库仓库ID
                    if(ToolUtil.isNotEmpty(inHouseId)){
                        if(ToolUtil.isNotEmpty(r.getXlbStorehouseId()) && !r.getXlbStorehouseId().equals(inHouseId.toString())){
                            continue;
                        }
                    }

                    goodsCount++;
                    HxOrderPutDetailed hxOrderPutDetailedParam = new HxOrderPutDetailed();
                    TcslOrderPutDetailed tcslOrderPutDetailed = new TcslOrderPutDetailed();


                    Object id1 = ((JSONObject) details1s).opt("id");//入库单明细ID
                    Object billId = ((JSONObject) details1s).opt("billId");//所属主单据ID
                    Object amount = ((JSONObject) details1s).opt("amount");//数量
                    Object mainUnitAmount = ((JSONObject) details1s).opt("mainUnitAmount");//最小单位数量
                    Object price = ((JSONObject) details1s).opt("price");//非税成本单价(含运费)
                    Object money = ((JSONObject) details1s).opt("money");//非税成本金额(含运费)
                    Object taxRate = ((JSONObject) details1s).opt("taxRate");//税率
                    Object taxRateMoney = ((JSONObject) details1s).opt("taxRateMoney");//税额
                    Object taxPrice = ((JSONObject) details1s).opt("taxPrice");//含税成本单价(含运费)
                    Object taxMoney = ((JSONObject) details1s).opt("taxMoney");//含税成本金额(含运费)
                    Object assistUnitAmount = ((JSONObject) details1s).opt("assistUnitAmount");//辅助数量
                    Object preDetailsAssistUnit = ((JSONObject) details1s).opt("preDetailsAssistUnit");//上级明细单位是否为辅助单位(0-否,1-是)
                    Object inPrice = ((JSONObject) details1s).opt("inPrice");//入库非税单价(不含运费)
                    Object inMoney = ((JSONObject) details1s).opt("inMoney");//入库非税金额(不含运费)
                    Object inTaxPrice = ((JSONObject) details1s).opt("inTaxPrice");//入库含税单价(不含运费)
                    Object inTaxMoney = ((JSONObject) details1s).opt("inTaxMoney");//入库含税金额(不含运费)
                    Object costTaxRate = ((JSONObject) details1s).opt("costTaxRate");//成本税率
                    Object inTaxRateMoney = ((JSONObject) details1s).opt("inTaxRateMoney");//入库税额
//                    Object inHouseId = ((JSONObject) details1s).opt("inHouseId");//入库仓库ID

                    Object inHouseName = ((JSONObject) details1s).opt("inHouseName");//入库仓库名称
                    Object inHouseCode = ((JSONObject) details1s).opt("inHouseCode");//入库仓库编码
                    Object outHouseId = ((JSONObject) details1s).opt("outHouseId");//出库仓库ID
                    Object outHouseName = ((JSONObject) details1s).opt("outHouseName");//出库仓库名称
                    Object outHouseCode = ((JSONObject) details1s).opt("outHouseCode");//出库仓库编码
                    Object unitId = ((JSONObject) details1s).opt("unitId");//单位id
                    Object unitName = ((JSONObject) details1s).opt("unitName");//单位名称
                    Object itemTypeId = ((JSONObject) details1s).opt("itemTypeId");//品项类别ID
                    Object itemTypeName = ((JSONObject) details1s).opt("itemTypeName");//品项类别名称
                    Object itemCode = ((JSONObject) details1s).opt("itemCode");//品项编号
                    Object itemId = ((JSONObject) details1s).opt("itemId");//品项ID
                    Object itemName = ((JSONObject) details1s).opt("itemName");//品项名称
                    Object itemSpec = ((JSONObject) details1s).opt("itemSpec");//品项规格
                    Object giftFlag = ((JSONObject) details1s).opt("giftFlag");//赠品标记0:否,1:是
                    Object carriageFee = ((JSONObject) details1s).opt("carriageFee");//运费
                    Object batchCode = ((JSONObject) details1s).opt("batchCode");//批次号
                    Object expectArrivalDate = ((JSONObject) details1s).opt("expectArrivalDate");//预期到货时间
                    Object detailMemo = ((JSONObject) details1s).opt("detailMemo");//明细备注


                    // 设置明细表字段
                    tcslOrderPutDetailed.setId(id1 != null ? id1.toString() : null);
                    tcslOrderPutDetailed.setBillId(billId != null ? billId.toString() : null);
                    tcslOrderPutDetailed.setAmount(amount != null ? new BigDecimal(amount.toString()) : null);
                    tcslOrderPutDetailed.setMainUnitAmount(mainUnitAmount != null ? new BigDecimal(mainUnitAmount.toString()) : null);
                    tcslOrderPutDetailed.setPrice(price != null ? new BigDecimal(price.toString()) : null);
                    tcslOrderPutDetailed.setMoney(money != null ? new BigDecimal(money.toString()) : null);
                    tcslOrderPutDetailed.setTaxRate(taxRate != null ? new BigDecimal(taxRate.toString()) : null);
                    tcslOrderPutDetailed.setTaxRateMoney(taxRateMoney != null ? new BigDecimal(taxRateMoney.toString()) : null);
                    tcslOrderPutDetailed.setTaxPrice(taxPrice != null ? new BigDecimal(taxPrice.toString()) : null);
                    tcslOrderPutDetailed.setTaxMoney(taxMoney != null ? new BigDecimal(taxMoney.toString()) : null);
                    tcslOrderPutDetailed.setAssistUnitAmount(assistUnitAmount != null ? new BigDecimal(assistUnitAmount.toString()) : null);
                    tcslOrderPutDetailed.setPreDetailsAssistUnit(preDetailsAssistUnit != null ? preDetailsAssistUnit.toString() : null);
                    tcslOrderPutDetailed.setInPrice(inPrice != null ? new BigDecimal(inPrice.toString()) : null);
                    tcslOrderPutDetailed.setInMoney(inMoney != null ? new BigDecimal(inMoney.toString()) : null);
                    tcslOrderPutDetailed.setInTaxPrice(inTaxPrice != null ? new BigDecimal(inTaxPrice.toString()) : null);
                    tcslOrderPutDetailed.setInTaxMoney(inTaxMoney != null ? new BigDecimal(inTaxMoney.toString()) : null);
                    tcslOrderPutDetailed.setCostTaxRate(costTaxRate != null ? new BigDecimal(costTaxRate.toString()) : null);
                    tcslOrderPutDetailed.setInTaxRateMoney(inTaxRateMoney != null ? new BigDecimal(inTaxRateMoney.toString()) : null);
                    tcslOrderPutDetailed.setInHouseId(inHouseId != null ? inHouseId.toString() : null);
                    tcslOrderPutDetailed.setInHouseName(inHouseName != null ? inHouseName.toString() : null);
                    tcslOrderPutDetailed.setInHouseCode(inHouseCode != null ? inHouseCode.toString() : null);
                    tcslOrderPutDetailed.setOutHouseId(outHouseId != null ? outHouseId.toString() : null);
                    tcslOrderPutDetailed.setOutHouseName(outHouseName != null ? outHouseName.toString() : null);
                    tcslOrderPutDetailed.setOutHouseCode(outHouseCode != null ? outHouseCode.toString() : null);
                    tcslOrderPutDetailed.setUnitId(unitId != null ? unitId.toString() : null);
                    tcslOrderPutDetailed.setUnitName(unitName != null ? unitName.toString() : null);
                    tcslOrderPutDetailed.setItemTypeId(itemTypeId != null ? itemTypeId.toString() : null);
                    tcslOrderPutDetailed.setItemTypeName(itemTypeName != null ? itemTypeName.toString() : null);
                    tcslOrderPutDetailed.setItemCode(itemCode != null ? itemCode.toString() : null);
                    tcslOrderPutDetailed.setItemId(itemId != null ? itemId.toString() : null);
                    tcslOrderPutDetailed.setItemName(itemName != null ? itemName.toString() : null);
                    tcslOrderPutDetailed.setItemSpec(itemSpec != null ? itemSpec.toString() : null);
//                    tcslOrderPutDetailed.setGiftFlag(giftFlag != null ? giftFlag.toString() : null);
                    if (giftFlag != null) {
                        if ("true".equals(giftFlag.toString()) || "1".equals(giftFlag.toString())) {
                            tcslOrderPutDetailed.setGiftFlag("1");
                        } else if ("false".equals(giftFlag.toString()) || "0".equals(giftFlag.toString())) {
                            tcslOrderPutDetailed.setGiftFlag("0");
                        } else {
                            tcslOrderPutDetailed.setGiftFlag("0"); // 默认值
                        }
                    } else {
                        tcslOrderPutDetailed.setGiftFlag("0"); // 默认值
                    }
                    tcslOrderPutDetailed.setCarriageFee(carriageFee != null ? new BigDecimal(carriageFee.toString()) : null);
                    tcslOrderPutDetailed.setBatchCode(batchCode != null ? batchCode.toString() : null);
//                    tcslOrderPutDetailed.setExpectArrivalDate(expectArrivalDate != null ? DateUtils.parseDate(expectArrivalDate.toString()) : null);
                    tcslOrderPutDetailed.setDetailMemo(detailMemo != null ? detailMemo.toString() : null);

                    tcslOrderPutDetailedList.add(tcslOrderPutDetailed);
                    this.tcslOrderPutDetailedService.saveBatch(tcslOrderPutDetailedList);
                    tcslOrderPutDetailedList.clear();



                    HxBasicGoodsParam hxBasicGoodsParamS = new HxBasicGoodsParam();
//                    hxBasicGoodsParamS.setGoodsTcslId(itemId.toString());

                    Map<String, String> itemIdToShelfLifeMap = new HashMap<>();
                    if (jsonItemObject.get("code").toString().equals("0")) {
                        JSONArray dataArray1 = jsonItemObject.getJSONArray("data");

                        List<Object> dataList1 = new ArrayList<>();
                        for (int i = 0; i < dataArray1.length(); i++) {
                            Object item = dataArray1.get(i);
                            dataList1.add(item);
                        }

                        for (Object data1 : dataList1) {
                            Object itemId1 = ((JSONObject) data1).opt("id");
                            Object shelfLife = ((JSONObject) data1).opt("shelfLife");
                            String itemIdStr = itemId1 != null ? itemId1.toString() : "";
                            String shelfLifeStr = shelfLife != null ? shelfLife.toString() : "";

                            itemIdToShelfLifeMap.put(itemIdStr, shelfLifeStr);
                        }
                    }


                    if (itemId != null) {
                        hxBasicGoodsParamS.setGoodsXlbId(itemId.toString());
                    } else {
                        hxBasicGoodsParamS.setGoodsXlbId("空"); // 或者设置默认值
                    }
                    hxBasicGoodsParamS.setGoodsCustomerId(r.getId());


                    HxBasicGoodsResult goods = hxBasicGoodsService.findBySpec(hxBasicGoodsParamS, user.getOperateId());
                    if (goods == null) {

                        AtomicReference<String> jibenUnit = new AtomicReference<>("");
                        AtomicReference<String> cgUnit = new AtomicReference<>("");
                        AtomicReference<String> kcUnit = new AtomicReference<>("");
                        AtomicReference<String> psUnit = new AtomicReference<>("");
                        AtomicReference<String> pfUnit = new AtomicReference<>("");

                        AtomicReference<String> kcRate = new AtomicReference<>("");
                        AtomicReference<String> cgRate = new AtomicReference<>("");
                        AtomicReference<String> pfRate = new AtomicReference<>("");
                        AtomicReference<String> psRate = new AtomicReference<>("");

                        if (jsonItemUnitObject.get("code").toString().equals("0")) {
                            JSONArray jsonItemUnitJSONArray = jsonItemUnitObject.getJSONArray("data");

                            jsonItemUnitJSONArray.forEach(itemUnitData -> {
                                JSONObject itemUnitData1 = (JSONObject) itemUnitData;
                                itemUnitData1 = (JSONObject) itemUnitData;
                                if ("1".equals(itemUnitData1.get("enableFlag").toString())
                                        && itemId.toString().equals(itemUnitData1.getString("itemId"))) {
                                    if ("1".equals(itemUnitData1.get("mainFlag").toString())) {
                                        jibenUnit.set(itemUnitData1.getString("name"));
                                        pfUnit.set(itemUnitData1.getString("name"));
                                        pfRate.set(itemUnitData1.get("ratio").toString());
                                        cgUnit.set(itemUnitData1.getString("name"));
                                        cgRate.set(itemUnitData1.get("ratio").toString());
                                        kcUnit.set(itemUnitData1.getString("name"));
                                        kcRate.set(itemUnitData1.get("ratio").toString());
                                        psUnit.set(itemUnitData1.getString("name"));
                                        psRate.set(itemUnitData1.get("ratio").toString());
                                    }
                                }
                            });

                            jsonItemUnitJSONArray.forEach(itemUnitData -> {
                                JSONObject itemUnitData1 = (JSONObject) itemUnitData;
                                itemUnitData1 = (JSONObject) itemUnitData;
                                if ("1".equals(itemUnitData1.get("enableFlag").toString())
                                        && itemId.toString().equals(itemUnitData1.getString("itemId"))) {
                                    if ("0".equals(itemUnitData1.get("mainFlag").toString())) {
                                        if ("1".equals(itemUnitData1.get("purchaseFlag").toString())) {
                                            cgUnit.set(itemUnitData1.getString("name"));
                                            cgRate.set(itemUnitData1.get("ratio").toString());
                                        }
                                        if ("1".equals(itemUnitData1.get("checkFirstFlag").toString())) {
                                            kcUnit.set(itemUnitData1.getString("name"));
                                            kcRate.set(itemUnitData1.get("ratio").toString());
                                        }
                                        if ("1".equals(itemUnitData1.get("salesFlag").toString())) {
                                            psUnit.set(itemUnitData1.getString("name"));
                                            psRate.set(itemUnitData1.get("ratio").toString());
                                        }
                                    }
                                }
                            });
                        }

                        HxBasicGoods hxBasicGoodsParam = new HxBasicGoods();
                        if (ToolUtil.isNotEmpty(itemId.toString()) && !itemId.toString().equals("null")) {
                            hxBasicGoodsParam.setGoodsXlbId(itemId.toString());
                        }
                        if (itemName != null && ToolUtil.isNotEmpty(itemName.toString()) && !itemName.toString().equals("null")) {
                            hxBasicGoodsParam.setGoodsName(itemName.toString());
                        }
//                        if (ToolUtil.isNotEmpty(itemBarCode.toString()) && !itemBarCode.toString().equals("null")) {
//                            hxBasicGoodsParam.setGoodsPcode69(itemBarCode.toString());
//                        }
                        if (itemCode != null && ToolUtil.isNotEmpty(itemCode.toString()) && !itemCode.toString().equals("null")) {
                            hxBasicGoodsParam.setGoodsNumber(itemCode.toString());
                        }
                        if (itemSpec != null && ToolUtil.isNotEmpty(itemSpec.toString()) && !itemSpec.toString().equals("null")) {
                            hxBasicGoodsParam.setGoodsSpecs(itemSpec.toString());
                        }
                        if (unitName != null && ToolUtil.isNotEmpty(unitName.toString()) && !unitName.toString().equals("null")) {
                            hxBasicGoodsParam.setJibenUnit(unitName.toString());
                        }

                        hxBasicGoodsParam.setJibenUnit(jibenUnit.get());//基本单位
                        hxBasicGoodsParam.setKcUnit(kcUnit.get());//库存单位
                        hxBasicGoodsParam.setKcRate(kcRate.get());//库存换算率
                        hxBasicGoodsParam.setCgUnit(cgUnit.get());//采购单位
                        hxBasicGoodsParam.setCgRate(cgRate.get());//采购换算率
                        hxBasicGoodsParam.setPfRate(pfRate.get());//批发换算率
                        hxBasicGoodsParam.setPfUnit(pfUnit.get());//批发单位
                        hxBasicGoodsParam.setPsRate(psRate.get());//配送换算率
                        hxBasicGoodsParam.setPsUnit(psUnit.get());//配送单位
                        hxBasicGoodsParam.setGoodsSpecs(itemSpec != null ? itemSpec.toString() : "");


                        hxBasicGoodsParam.setPsUnit(unitName.toString());
                        hxBasicGoodsParam.setCreateTime(new Date());
                        hxBasicGoodsParam.setCreateName(user.getName());
                        hxBasicGoodsParam.setDeliverId(user.getDeliverId());
                        hxBasicGoodsParam.setDeptId(user.getDeptId());
                        hxBasicGoodsParam.setGoodsCustomerName(r.getCustomerName());
                        hxBasicGoodsParam.setGoodsCustomerId(r.getId());
                        hxBasicGoodsParam.setGoodsBottom("10");
                        hxBasicGoodsParam.setGoodsLamination("10");
                        hxBasicGoodsParam.setGoodsTraylayer("1");
                        hxBasicGoodsParam.setGoodsSupportvolume("100");
                        hxBasicGoodsParam.setAnquanNum("14");
                        hxBasicGoodsParam.setLength("0");
                        hxBasicGoodsParam.setHeight("0");
                        hxBasicGoodsParam.setWidth("0");
                        hxBasicGoodsParam.setDismantlingParts("否");

                        hxBasicGoodsParam.setGoodsChargingCg("0");
                        hxBasicGoodsParam.setGoodsChargingPf("0");
                        hxBasicGoodsParam.setGoodsChargingPs("0");
                        hxBasicGoodsParam.setGoodsVolume("0.015");
                        hxBasicGoodsParam.setGoodsWeight("0.015");


                        hxBasicGoodsParam.setGoodsBigtypedictId(Long.valueOf(itemTypeId.toString()));
                        hxBasicGoodsParam.setGoodsBigtype(itemTypeName.toString());

                        String shelfLife = itemIdToShelfLifeMap.get(itemId);
                        if (ToolUtil.isEmpty(shelfLife)) {
                            hxBasicGoodsParam.setGoodsWarranty("36");
                        }else {
                            hxBasicGoodsParam.setGoodsWarranty(shelfLife);
                        }
                        hxBasicGoodsService.save(hxBasicGoodsParam);

                        goods = new HxBasicGoodsResult();
                        ToolUtil.copyProperties(goods, hxBasicGoodsParam);
                        hxOrderPutDetailedParam.setGoodsId(hxBasicGoodsParam.getId().longValue());

                    } else {

                        hxOrderPutDetailedParam.setGoodsId(goods.getId().longValue());
                    }


                    hxOrderPutDetailedParam.setOrderPutNumber(String.valueOf(sysBillCode));
                    hxOrderPutDetailedParam.setGoodsName(itemName != null ? itemName.toString() : "");
                    hxOrderPutDetailedParam.setGoodsSpecs(itemSpec != null ? itemSpec.toString() : "");
                    hxOrderPutDetailedParam.setGoodsNumber(itemCode != null ? itemCode.toString() : "");
                    hxOrderPutDetailedParam.setUnit(unitName != null ? unitName.toString() : "");
                    hxOrderPutDetailedParam.setJibenNum(mainUnitAmount != null ? mainUnitAmount.toString() : "");
                    hxOrderPutDetailedParam.setBatch(batchCode != null ? batchCode.toString() : "");
                    hxOrderPutDetailedParam.setGoodsVolume("0");
                    hxOrderPutDetailedParam.setGoodsWeight("0");
                    hxOrderPutDetailedParam.setPutVolume("0");
                    hxOrderPutDetailedParam.setDismantlingParts("否");


                    HxBasicGoods existingGoods = hxBasicGoodsService.lambdaQuery()
                            .eq(HxBasicGoods::getGoodsXlbId, itemId.toString())
                            .one();
                    if (existingGoods != null) {
                        hxOrderPutDetailedParam.setRate(existingGoods.getKcRate());
                        hxOrderPutDetailedParam.setJibenUnit(existingGoods.getJibenUnit());
                    }
                    if (giftFlag != null && "1".equals(giftFlag.toString())) {
                        // 是赠品的情况
                        hxOrderPutDetailedParam.setZpUnit(unitName != null ? unitName.toString() : "");
                        hxOrderPutDetailedParam.setZpRate(existingGoods.getKcRate());
                        hxOrderPutDetailedParam.setZpNum(String.valueOf(amount));
                        hxOrderPutDetailedParam.setZpJibenNum(String.valueOf(mainUnitAmount));

                    } else {
                        // 不是赠品的情况
                        hxOrderPutDetailedParam.setZpUnit(" ");
                        hxOrderPutDetailedParam.setZpRate(" ");
                        hxOrderPutDetailedParam.setZpNum(" ");
                        hxOrderPutDetailedParam.setZpJibenNum(" ");
                    }

                    if (detailMemo != null && ToolUtil.isNotEmpty(detailMemo.toString()) && !detailMemo.toString().equals("null")) {
                        hxOrderPutDetailedParam.setNotes(detailMemo.toString());
                    } else {
                        hxOrderPutDetailedParam.setNotes(""); // 设置默认值
                    }


                   hxOrderPutDetailedParam.setSumNum(String.valueOf(amount));

                    hxOrderPutDetailedParam.setNum(String.valueOf(amount));


                    if (ToolUtil.isNotEmpty(goods.getGoodsSupportvolume())) {
                        hxOrderPutDetailedParam.setGoodsSupportvolume(goods.getGoodsSupportvolume());
                    } else {
                        hxOrderPutDetailedParam.setGoodsSupportvolume("100");
                    }

                    if (ToolUtil.isNotEmpty(goods.getGoodsWeight())) {
                        hxOrderPutDetailedParam.setGoodsWeight(goods.getGoodsWeight());
                    } else {
                        hxOrderPutDetailedParam.setGoodsWeight("0.015");
                    }
                    BigDecimal numsweight = new BigDecimal(0);
                    if (ToolUtil.isNotEmpty(goods.getGoodsWeight())) {
                        numsweight = new BigDecimal(goods.getGoodsWeight());
                    }
                    //采购重量
                    BigDecimal multiply4 = numsweight.multiply(new BigDecimal(amount.toString()));

                    hxOrderPutDetailedParam.setPutWeight(String.valueOf(multiply4));
                    BigDecimal cgPrice = new BigDecimal(10);
                    if (ToolUtil.isNotEmpty(goods.getGoodsChargingCg())) {
                        cgPrice = new BigDecimal(goods.getGoodsChargingCg());
                    }

//                    BigDecimal result = cgPrice.multiply(new BigDecimal(sumNum)).multiply(new BigDecimal(purchaseRatio.toString()));
                    hxOrderPutDetailedParam.setPutMoney(inTaxMoney.toString());
//                    BigDecimal result1 = cgPrice.multiply(new BigDecimal(purchaseRatio.toString()));

                    hxOrderPutDetailedParam.setGoodsPrice(inTaxPrice.toString());

                    hxOrderPutDetailedParam.setUnitType("采购单位");
                    hxOrderPutDetailedParam.setXlbOrderPutNumber(String.valueOf(billId));


                    if (ToolUtil.isNotEmpty(sysBillCode) && !sysBillCode.equals("null")) {//单据号
                        // 校验是否已经添加过
                        Integer count = hxOrderPutDetailedService.lambdaQuery()
                                .eq(HxOrderPutDetailed::getOrderPutNumber, sysBillCode)
                                .count();
                        if (count ==  goodsCount) {
                            continue; // 如果数据库中已存在该订单号，则跳过当前循环
                        }
                    }

                    Date date = new Date();
                    if (ToolUtil.isNotEmpty(expectArrivalDate.toString()) && !expectArrivalDate.toString().equals("null")) {
                        hxOrderPutParam.setYuyueTime(expectArrivalDate.toString());// 预约时间
                    } else {

                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String dateString = dateFormat.format(date);
                        hxOrderPutParam.setYuyueTime(dateString);// 预约时间
                    }
                    hxOrderPutDetailedList.add(hxOrderPutDetailedParam);
                }

                if(hxOrderPutDetailedList.size() < 1){
                    continue;
                }

                hxOrderPutParam.setGoodsNum(String.valueOf(goodsCount));

                if (ToolUtil.isNotEmpty(sysBillCode) && !sysBillCode.equals("null")) {//单据号
                    // 校验是否已经添加过
                    Integer count = hxOrderPutService.lambdaQuery()
                            .eq(HxOrderPut::getOrderPutNumber, sysBillCode)
                            .ne(HxOrderPut::getOrderState, "作废")
                            .count();
                    if (count > 0) {
                        continue; // 如果数据库中已存在该订单号，则跳过当前循环
                    }
                }

                this.hxOrderPutDetailedService.saveBatch(hxOrderPutDetailedList);
                hxOrderPutDetailedList.clear();


                hxOrderPutParam.setOrderPutNumber(String.valueOf(sysBillCode));

                if(ToolUtil.isNotEmpty(otherOrganId)){
                    BasicPutgoods basicPutgoods = basicPutgoodsService.lambdaQuery()
                            .eq(BasicPutgoods::getPutgoodsCustomerId, r.getId())
                            .eq(BasicPutgoods::getXlbClientId, otherOrganId.toString())
                            .eq(BasicPutgoods::getPutgoodsName, otherOrganName.toString())
                            .last("limit 1")
                            .one();
                    if (basicPutgoods == null) {
                        BasicPutgoods bpgp3 = new BasicPutgoods();
                        bpgp3.setPutgoodsCustomerId(r.getId());
                        bpgp3.setPutgoodsOperateName(r.getCustomerName());
                        bpgp3.setPutgoodsName(otherOrganName.toString());//单位名称
                        bpgp3.setUnitNumber(otherOrganCode.toString());
//                    bpgp3.setPutgoodsAddress(clientName.toString());
                        bpgp3.setUnitType("供应商");
                        bpgp3.setDictId(0l);
                        bpgp3.setDeliverId(user.getDeliverId());
                        bpgp3.setDeptId(user.getDeptId());
                        bpgp3.setXlbClientId(otherOrganId.toString());

                        basicPutgoodsService.save(bpgp3);

                        BasicAddress bap3 = new BasicAddress();
                        bap3.setPutgoodsId(Long.parseLong(bpgp3.getId().toString()));
                        bap3.setPutgoodsName(otherOrganName.toString());//单位名称
                        bap3.setAddress(otherOrganName.toString());//地点 为单位名称
                        bap3.setLongitude("0");
                        bap3.setLatitude("0");
                        bap3.setSwitchWl("1");
                        bap3.setSwitchBj("1500");//提货围栏半径 默认100米
                        bap3.setSwitchBj2("2000");//收货围栏半径 默认100米
                        basicAddressService.save(bap3);
                    }
                }

                hxOrderPutParam.setSetUnit(tradeOrganClassName2.toString());//发货客户
                hxOrderPutParam.setGetWarehouse(w.getWarehouseName());// 收货仓库名称
                hxOrderPutParam.setGetWarehouseId(setWarehouseId);//收货仓库id

                if(ToolUtil.isNotEmpty(otherOrganId)){
                    hxOrderPutParam.setGetUnitId(Long.valueOf(otherOrganId.toString()));
                }
                if(ToolUtil.isNotEmpty(otherOrganName)){
                    hxOrderPutParam.setGetUnit(otherOrganName.toString());
                }
                if(ToolUtil.isNotEmpty(organName)){
                    hxOrderPutParam.setSetUnit(organName.toString());
                }
                if(ToolUtil.isNotEmpty(organId)){
                    hxOrderPutParam.setSetUnitId(Long.valueOf(organId.toString()));
                }

                hxOrderPutParam.setPutNum("0");
                hxOrderPutParam.setPutVolume("0");
                hxOrderPutParam.setXlbOrderId(String.valueOf(id));
                hxOrderPutParam.setReturnStatus("待返回");


                Date date = new Date();
                hxOrderPutParam.setCreateTime(date);// 创建时间
                if (billType != null) {
                    if (billType.toString().equals("1001")) {
                        hxOrderPutParam.setOrderType("期初入库单");
                    }
                    if (billType.toString().equals("1002")) {
                        hxOrderPutParam.setOrderType("采购入库单");
                    }
                    if (billType.toString().equals("1003")) {
                        hxOrderPutParam.setOrderType("其他入库单");
                    }
                    if (billType.toString().equals("1004")) {
                        hxOrderPutParam.setOrderType("盘点入库单");
                    }
                    if (billType.toString().equals("1005")) {
                        hxOrderPutParam.setOrderType("差异入库单");
                    }
                    if (billType.toString().equals("1006")) {
                        hxOrderPutParam.setOrderType("调拨入库单");
                    }
                    if (billType.toString().equals("1007")) {
                        hxOrderPutParam.setOrderType("采购退货");
                    }
                    if (billType.toString().equals("1008")) {
                        hxOrderPutParam.setOrderType("冲减返库");
                    }
                    if (billType.toString().equals("1009")) {
                        hxOrderPutParam.setOrderType("销售返库(蓝字)");
                    }
                    if (billType.toString().equals("1100")) {
                        hxOrderPutParam.setOrderType("组合加工单成品入库");
                    }
                } else {
                    hxOrderPutParam.setOrderType(" ");
                }
                hxOrderPutParam.setOrderState("待提交");
                //备注
                if (memo != null) {
                    hxOrderPutParam.setNotes(memo.toString());
                } else {
                    hxOrderPutParam.setNotes(""); // 设置默认值
                }

// 对 inCreateManName 进行空值检查
                if (inCreateManName != null) {
                    hxOrderPutParam.setCreateUserName(inCreateManName.toString());
                } else {
                    hxOrderPutParam.setCreateUserName(""); // 设置默认值
                }

// 对 operateManName 进行空值检查
                if (operateManName != null) {
                    hxOrderPutParam.setSubmitUserName(operateManName.toString());
                } else {
                    hxOrderPutParam.setSubmitUserName(""); // 设置默认值
                }
                hxOrderPutParam.setDeptId(user.getDeptId());
                hxOrderPutParam.setDeliverId(user.getDeliverId());
                hxOrderPutParam.setCustomerId((long) r.getId());
                hxOrderPutParam.setCustomerName(r.getCustomerName());
                hxOrderPutList.add(hxOrderPutParam);

            }
            this.hxOrderPutService.saveBatch(hxOrderPutList);
            hxOrderPutList.clear();
        }

        return ResponseData.success();

    }

    /**
     * 跳转到tcsl预约拉取页面
     *
     * @author zhucx
     * @Date 2023-08-05
     */
    @RequestMapping("tcslYuyue")
    public String totcslYuyue(Model model) {

        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId, deliverId, user.getOperateId()));
        model.addAttribute("wlist", basicWarehouseService.findAvailableList(deptId, deliverId, user.getOperateId()));

        return PREFIX + "/tcslYuyue.html";
    }



    /**
     * 预约任务确认
     */
    @RequestMapping("/confirm")
    @ResponseBody
    public ResponseData confirm(@RequestParam("id") Long id, @RequestParam("yuyueTime") String yuyueTime) {
        User user = userService.getcurrentUser();
        ResponseData data = new ResponseData();
        lock.lock();//获取锁
        try {
            //批量生成入库单 ，托盘
            //判断明细是否添加了
            HxOrderPut hxOrderPut = hxOrderPutService.getById(id);
            hxOrderPut.setYuyueTime(yuyueTime);
            if ("待确认".equals(hxOrderPut.getOrderState())) {
                QueryWrapper <HxOrderPutDetailed> queryWrapper = new QueryWrapper <HxOrderPutDetailed>();
                queryWrapper.eq("xlb_order_put_number", hxOrderPut.getXlbOrderId());
                int count = hxOrderPutDetailedService.count(queryWrapper);
                if (count > 0) {
//					this.yuYueConfirm(hxOrderPut);//确认预约的方法
                    hxStoragePutDetailedService.submissionOrder(hxOrderPut);

                } else {
                    data.setSuccess(false);
                    data.setMessage("请先添加商品明细，单号：" + hxOrderPut.getOrderPutNumber());
                    return data;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//释放锁
        }
        return ResponseData.success();
    }


    /**
     * 新零帮预约任务确认
     *
     * @author
     * @Date 2024-04-19
     */

    private ResponseData yuYueConfirm(HxOrderPut hxOrderPut) {
        ResponseData data = new ResponseData();

        BasicCustomer r = basicCustomerService.getById(hxOrderPut.getCustomerId());


        String url = "https://test-api.xlbsoft.com/api/hxl.open.wms.appointmentorder.confirm";
//     	String url = "https://hxl-api.xlbsoft.com/api/hxl.open.wms.appointmentorder.confirm";


        BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
        oauth2tokenParam.setDeliverId(r.getDeliverId());
        oauth2tokenParam.setGsnumber(r.getGsnumber());
        BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);


        // 预约任务确认
        JSONObject json = new JSONObject();
        json.put("id", hxOrderPut.getXlbOrderId());//在入库订单表查询到新零帮到货预约id
        json.put("appoint_time", hxOrderPut.getYuyueTime());

        String response = HttpRequest.post(url)
                .timeout(60000)
                .header("Authorization", "Bearer " + oauth2tokenResult.getOauth2TokenXlb())
                .body(json.toString()).execute().body();
        JSONObject jsonObject = new JSONObject(response);
        if (jsonObject.get("code").toString().equals("0")) {
            //确认预约任务是否成功
//			hxOrderPutService.lambdaUpdate()
//					.eq(HxOrderPut::getXlbOrderId, hxOrderPut.getXlbOrderId())
//					.set(HxOrderPut::getOrderState, "收货中")
//					.update();
        } else {

            //System.out.println(jsonObject.toString());

            data.setSuccess(false);
            data.setMessage("确认预约任务失败");
        }


        return data;
    }


    /**
     * 跳转到主页面
     *
     * @author zhucx
     * @Date 2023-08-05
     */
    @RequestMapping("")
    public String index(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId, deliverId, user.getOperateId()));
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/hxOrderPut.html";
    }

    /**
     * 跳转到查询页面
     *
     * @author zhucx
     * @Date 2023-08-05
     */
    @RequestMapping("toQuery")
    public String toQuery(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId, deliverId, user.getOperateId()));
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/query.html";
    }

    /**
     * 跳转到退货页面
     *
     * @author zhucx
     * @Date 2023-08-05
     */
    @RequestMapping("toReturnGoods")
    public String toReturnGoods(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId, deliverId, user.getOperateId()));
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/returnGoods.html";
    }


    /**
     * 跳转到拉取新零帮门店退货单页面
     *
     * @author lww
     * @Date 2024-04-23
     */
    @RequestMapping("xlbReturn")
    public String xlbReturn(Model model) {

        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId, deliverId, user.getOperateId()));
//查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId, deliverId, user.getOperateId()));

        return PREFIX + "/xlbReturn.html";
    }


    /**
     * 跳转到处理新零帮门店退货单页面
     *
     * @author zhucx
     * @Date 2023-08-05
     */
    @RequestMapping("xlbReturnChu")
    public String xlbReturnChu() {
        return PREFIX + "/xlbReturnChu.html";
    }


    /**
     * 处理新零帮门店退货单
     */
    @RequestMapping("/xlbChuLi")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class, timeout = 800000)
    public ResponseData xlbChuLi(Integer id, String orderType, String canTwoSell) {
        User user = userService.getcurrentUser();
        ResponseData data = new ResponseData();
        HxOrderPut hxOrderPut = hxOrderPutService.getById(id);
        BasicCustomer r = basicCustomerService.getById(hxOrderPut.getCustomerId());

        if (hxOrderPut.getOrderState().equals("待处理")) {
            String url = "https://hxl-api.xlbsoft.com/api/hxl.open.storeapplicationorder.handle";
            //			String url = "https://hxl-api.xlbsoft.com/api/hxl.open.storeapplicationorder.handle";

            BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
            oauth2tokenParam.setDeliverId(r.getDeliverId());
            oauth2tokenParam.setGsnumber(r.getGsnumber());
            BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);


            // 预约任务确认
            JSONObject json = new JSONObject();
            json.put("can_two_sell", canTwoSell);
            json.put("fid", hxOrderPut.getXlbOrderId());
            json.put("refuse", orderType);
            json.put("operator", user.getName());//操作人

            String response = HttpRequest.post(url)
                    .header("Authorization", "Bearer " + oauth2tokenResult.getOauth2TokenXlb())
                    .body(json.toString()).execute().body();
            //System.out.println(json);
            JSONObject jsonObject = new JSONObject(response);
            if (jsonObject.get("code").toString().equals("0")) {
                if (orderType.equals("false")) {
                    hxOrderPutService.lambdaUpdate()
                            .eq(HxOrderPut::getId, id)
                            .set(HxOrderPut::getOrderState, "待提交")
                            .update();
                }else if (orderType.equals("true")) {
                    hxOrderPutService.lambdaUpdate()
                            .eq(HxOrderPut::getId, id)
                            .set(HxOrderPut::getOrderState, "处理拒绝")
                            .update();
                }

                //System.out.println(jsonObject.toString());
            } else {
                //System.out.println(jsonObject.toString());
            }
        } else {
            data.setSuccess(false);
            data.setMessage("该订单不可处理，单号：" + hxOrderPut.getOrderPutNumber());
            return data;
        }

        return ResponseData.success();
    }


    /**
     * 查询新零帮门店退货单
     *
     * @author1
     * @Date 2024-04-17
     */
    @RequestMapping("/findReturn")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class, timeout = 800000)
    public ResponseData findReturn(String modified_yuyue, Integer customerId, Long setWarehouseId) throws IOException {
        User user = userService.getcurrentUser();

        BasicCustomer r = basicCustomerService.getById(customerId);
        BasicWarehouse w = basicWarehouseService.getById(setWarehouseId);

        if (ToolUtil.isEmpty(r.getGsnumber())) {
            return ResponseData.error("请维护新零帮公司号");
        }
        if (ToolUtil.isEmpty(r.getStoreIdXlb())) {
            return ResponseData.error("请维护门店id");
        }
        if (ToolUtil.isEmpty(w.getWarehouseXlbId())) {
            return ResponseData.error("请维护新零帮仓库id");
        }
        //String url = "https://test-api.xlbsoft.com/api/hxl.open.storeapplicationorder.findbyupdatetime";
        String url = "https://hxl-api.xlbsoft.com/api/hxl.open.storeapplicationorder.findbyupdatetime";


        JSONObject json = new JSONObject();
        json.put("store_id", r.getStoreIdXlb());
        json.put("storehouse_id", w.getWarehouseXlbId());
        json.put("update_time", modified_yuyue);
        BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
        oauth2tokenParam.setDeliverId(r.getDeliverId());
        oauth2tokenParam.setGsnumber(r.getGsnumber());
        BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
        String response = HttpRequest.post(url)
                .header("Authorization", "Bearer " + oauth2tokenResult.getOauth2TokenXlb())
                .body(json.toString()).execute().body();
        ObjectMapper objectMapper = new ObjectMapper();
        JSONObject jsonObject = new JSONObject(response);

        if (jsonObject.get("code").toString().equals("0")) {
            JSONArray dataArray = jsonObject.getJSONArray("data");
            List <HxOrderPut> hxOrderPutList = new ArrayList <>();
            List <HxOrderPutDetailed> hxOrderPutDetailedList = new ArrayList <>();
            for (Object data : dataArray) {
                HxOrderPut hxOrderPutParam = new HxOrderPut();
                Object approveBy = ((JSONObject) data).get("approve_by");// 批复人
                Object approveMoney1 = ((JSONObject) data).get("approve_money");// 批复金额
                Object approveTime = ((JSONObject) data).get("approve_time");// 批复时间
                Object auditBy = ((JSONObject) data).get("audit_by");// 审核人
                Object auditTime = ((JSONObject) data).get("audit_time");// 审核时间
                Object companyId = ((JSONObject) data).get("company_id");// 公司id
                Object createBy = ((JSONObject) data).get("create_by");// 创建人
                Object createTime = ((JSONObject) data).get("create_time");// 创建时间

                Object detailsObject = ((JSONObject) data).opt("details"); // 使用 opt 方法获取字段值，避免抛出异常

                if (detailsObject instanceof JSONArray) {
                    JSONArray detailsArray = (JSONArray) detailsObject;
                    for (Object detail : detailsArray) {
                        Object accountMethod = ((JSONObject) detail).get("account_method");// 核算方式
                        Object approveBatchNumber = ((JSONObject) detail).get("approve_batch_number");// 批复批次号
                        Object approveExpireDate = ((JSONObject) detail).get("approve_expire_date");// 批复过期日期
                        Object approveMemo = ((JSONObject) detail).get("approve_memo");// 批复备注
                        Object approveMoney = ((JSONObject) detail).get("approve_money");// 批复金额
                        Object approvePrice = ((JSONObject) detail).get("approve_price");// 批复单价
                        Object approveProducingDate = ((JSONObject) detail).get("approve_producing_date");// 批复生产日期
                        Object approveQuantity = ((JSONObject) detail).get("approve_quantity");// 批复数量
                        Object approveRatio = ((JSONObject) detail).get("approve_ratio");// 批复换算率
                        Object approveUnit = ((JSONObject) detail).get("approve_unit");// 批复单位
                        Object basicApprovePrice = ((JSONObject) detail).get("basic_approve_price");// 批复基本单价
                        Object basicApproveQuantity = ((JSONObject) detail).get("basic_approve_quantity");// 批复基本数量
                        Object basicUnit = ((JSONObject) detail).get("basic_unit");//基本单位
                        Object basicPrice = ((JSONObject) detail).get("basic_price");//基本单价
                        Object basicQuantity = ((JSONObject) detail).get("basic_quantity");//基本数量
                        Object batchId = ((JSONObject) detail).get("batch_id");//批次标识
                        Object batchNumber = ((JSONObject) detail).get("batch_number");//批次号
                        Object batchNumberFlag = ((JSONObject) detail).get("batch_number_flag");//是否可以选批次
                        Object categoryId = ((JSONObject) detail).get("category_id");//分类id
                        Object deliveryRatio = ((JSONObject) detail).get("delivery_ratio");//配送单位换算率
                        Object deliveryUnit = ((JSONObject) detail).get("delivery_unit");//配送单位
                        Object detailNum = ((JSONObject) detail).get("detail_num");//序号
                        Object expireDate = ((JSONObject) detail).get("expire_date");//到期日期
                        Object expireDateFlag = ((JSONObject) detail).get("expire_date_flag");//是否可以选到期日期
                        Object fid = ((JSONObject) detail).get("fid");//单据号
                        Object inStorehouseId = ((JSONObject) detail).get("in_storehouse_id");//调入仓库id
                        Object inStorehouseName = ((JSONObject) detail).get("in_storehouse_name");//调入仓库
                        Object itemBarCode = ((JSONObject) detail).get("item_bar_code");//商品条码
                        Object itemCode = ((JSONObject) detail).get("item_code");//商品代码
                        Object itemId = ((JSONObject) detail).get("item_id");//商品id
                        Object itemName = ((JSONObject) detail).get("item_name");//商品名称
                        Object itemSpec = ((JSONObject) detail).get("item_spec");//商品规格
                        String memo = ((JSONObject) detail).get("memo").toString();//备注
                        Object period = ((JSONObject) detail).get("period");//保质期
                        Object price = ((JSONObject) detail).get("price");//发货单价
                        Object producingDate = ((JSONObject) detail).get("producing_date");//生产日期
                        Object producingDateFlag = ((JSONObject) detail).get("producing_date_flag");//是否可以选生产日期
                        Object purchaseRatio = ((JSONObject) detail).get("purchase_ratio");//采购单位换算率
                        Object purchaseUnit = ((JSONObject) detail).get("purchase_unit");//采购单位
                        Object ratio = ((JSONObject) detail).get("ratio");//换算率
                        Object quantity = ((JSONObject) detail).get("quantity");//数量
                        Object shorthandCode = ((JSONObject) detail).get("shorthand_code");// 速记码
                        Object stockRatio = ((JSONObject) detail).get("stock_ratio");//库存单位换算率
                        Object stockUnit = ((JSONObject) detail).get("stock_unit");//库存单位
                        Object supplierFlag = ((JSONObject) detail).get("supplier_flag");//是否可编辑供应商
                        Object unit = ((JSONObject) detail).get("unit");//单位
                        Object wholesaleRatio = ((JSONObject) detail).get("wholesale_ratio");//批发单位换算率
                        Object wholesaleUnit = ((JSONObject) detail).get("wholesale_unit");//批发单位

                        HxOrderPutDetailed hxOrderPutDetailedParam = new HxOrderPutDetailed();

                        HxBasicGoodsParam hxBasicGoodsParamS = new HxBasicGoodsParam();
                        hxBasicGoodsParamS.setGoodsXlbId(itemId.toString());
                        hxBasicGoodsParamS.setGoodsCustomerId(r.getId());

                        HxBasicGoodsResult goodsid = hxBasicGoodsService.findBySpec(hxBasicGoodsParamS, user.getOperateId());

//						HxBasicGoods goodsid = hxBasicGoodsService.lambdaQuery()
//								.eq(HxBasicGoods::getGoodsXlbId, itemId.toString())
//								.one();

                        if (goodsid == null) {
                            HxBasicGoods hxBasicGoodsParam = new HxBasicGoods();
                            hxBasicGoodsParam.setGoodsXlbId(itemId.toString());
                            hxBasicGoodsParam.setGoodsName(itemName.toString());
                            hxBasicGoodsParam.setGoodsPcode69(itemBarCode.toString());
                            hxBasicGoodsParam.setGoodsNumber(itemCode.toString());
                            hxBasicGoodsParam.setGoodsSpecs(itemSpec.toString());
                            hxBasicGoodsParam.setJibenUnit(basicUnit.toString());
                            hxBasicGoodsParam.setKcUnit(stockUnit.toString());
                            hxBasicGoodsParam.setKcRate(String.valueOf(stockRatio));
                            hxBasicGoodsParam.setCgUnit(purchaseUnit.toString());
                            hxBasicGoodsParam.setCgRate(String.valueOf(purchaseRatio));
                            hxBasicGoodsParam.setPfRate(String.valueOf(wholesaleRatio));
                            hxBasicGoodsParam.setPfUnit(wholesaleUnit.toString());
                            hxBasicGoodsParam.setPsRate(String.valueOf(deliveryRatio));
                            hxBasicGoodsParam.setPsUnit(deliveryUnit.toString());
                            hxBasicGoodsParam.setCreateTime(new Date());
                            hxBasicGoodsParam.setCreateName(user.getName());
                            hxBasicGoodsParam.setDeliverId(user.getDeliverId());
                            hxBasicGoodsParam.setDeptId(user.getDeptId());
                            hxBasicGoodsParam.setGoodsCustomerName(r.getCustomerName());
                            hxBasicGoodsParam.setGoodsCustomerId(r.getId());
                            hxBasicGoodsParam.setGoodsBottom("10");
                            hxBasicGoodsParam.setGoodsLamination("10");
                            hxBasicGoodsParam.setGoodsTraylayer("1");
                            hxBasicGoodsParam.setGoodsSupportvolume("100");
                            hxBasicGoodsParam.setAnquanNum("14");
                            hxBasicGoodsParam.setGoodsWeight("0.1");
                            hxBasicGoodsParam.setGoodsChargingCg("10");
                            hxBasicGoodsParam.setGoodsChargingPf("10");
                            hxBasicGoodsParam.setGoodsChargingPs("10");
                            hxBasicGoodsParam.setGoodsVolume("0.1");

                            if (ToolUtil.isNotEmpty(period.toString()) && !period.toString().equals("null")) {


                                Pattern pattern = Pattern.compile("(\\d+)");
                                Matcher matcher = pattern.matcher(period.toString());

                                if (matcher.find()) {
                                    String number = matcher.group(1);
                                    int periods = Integer.parseInt(number);
                                    hxBasicGoodsParam.setGoodsWarranty(String.valueOf(periods / 30));
                                } else {
                                    // 未找到匹配的数字
                                }
                            } else {
                                hxBasicGoodsParam.setGoodsWarranty("36");
                            }

                            hxBasicGoodsService.save(hxBasicGoodsParam);

                            hxOrderPutDetailedParam.setGoodsId(hxBasicGoodsParam.getId().longValue());
                            goodsid = hxBasicGoodsService.findBySpec(hxBasicGoodsParamS, user.getOperateId());
                        } else {

                            hxOrderPutDetailedParam.setGoodsId(goodsid.getId().longValue());
                        }

                        hxOrderPutDetailedParam.setOrderPutNumber(String.valueOf(fid));
                        hxOrderPutDetailedParam.setGoodsName(itemName.toString());
                        hxOrderPutDetailedParam.setGoodsSpecs(itemSpec.toString());
                        hxOrderPutDetailedParam.setGoodsPcode69(itemBarCode.toString());
                        hxOrderPutDetailedParam.setGoodsNumber(itemCode.toString());
//					hxOrderPutDetailedParam.setNotes("");// 备注


                        BigDecimal decimal = new BigDecimal(purchaseRatio.toString());
                        BigDecimal bigDecimal = new BigDecimal(quantity.toString());
                        BigDecimal ratio1 = new BigDecimal(ratio.toString());
                        BigDecimal multiply = ratio1.multiply(bigDecimal);
                        BigDecimal divide = multiply.divide(decimal, 4, RoundingMode.HALF_DOWN);

                        hxOrderPutDetailedParam.setNum(String.valueOf(quantity));
                        hxOrderPutDetailedParam.setJibenUnit(basicUnit.toString());
                        hxOrderPutDetailedParam.setJibenNum(multiply.toString());
                        hxOrderPutDetailedParam.setUnit(unit.toString());
                        hxOrderPutDetailedParam.setRate(String.valueOf(ratio));

                        hxOrderPutDetailedParam.setSumNum(String.valueOf(quantity));
                        hxOrderPutDetailedParam.setPutMoney(String.valueOf(approveMoney.toString()));
//                        System.out.println("================================"+goodsid);
                        hxOrderPutDetailedParam.setGoodsSupportvolume(goodsid.getGoodsSupportvolume());
                        hxOrderPutDetailedParam.setGoodsWeight(goodsid.getGoodsWeight());
                        BigDecimal nums13 = new BigDecimal(goodsid.getGoodsWeight());
                        BigDecimal multiply12 = nums13.multiply(new BigDecimal(quantity.toString()));
                        hxOrderPutDetailedParam.setPutWeight(multiply12.multiply(nums13).toString());
                        hxOrderPutDetailedParam.setGoodsVolume(goodsid.getGoodsVolume());
                        BigDecimal nums11 = new BigDecimal(goodsid.getGoodsVolume());
                        BigDecimal multiply2 = nums11.multiply(new BigDecimal(quantity.toString()));
                        hxOrderPutDetailedParam.setPutVolume(nums11.multiply(multiply2).toString());
                        hxOrderPutDetailedParam.setZpNum("0");
                        hxOrderPutDetailedParam.setZpJibenNum("0");
                        hxOrderPutDetailedParam.setZpRate(String.valueOf(ratio1));
                        hxOrderPutDetailedParam.setZpUnit(String.valueOf(unit));
                        BigDecimal cgPrice = new BigDecimal(goodsid.getGoodsChargingCg());
                        BigDecimal result = cgPrice.multiply(new BigDecimal(quantity.toString()));
                        hxOrderPutDetailedParam.setPutMoney(result.toString());
                        BigDecimal result1 = cgPrice.multiply(new BigDecimal(goodsid.getCgRate()));
                        hxOrderPutDetailedParam.setGoodsPrice(result1.toString());
                        hxOrderPutDetailedParam.setXlbOrderPutNumber(String.valueOf(fid));
                        if (ratio1.compareTo(new BigDecimal("1")) == 0) {
                            hxOrderPutDetailedParam.setUnitType("基本单位");
                        } else if (ratio1.toString().equals(goodsid.getCgRate())) {
                            hxOrderPutDetailedParam.setUnitType("采购单位");
                        } else if (ratio1.toString().equals(goodsid.getPfRate())) {
                            hxOrderPutDetailedParam.setUnitType("批发单位");
                        } else if (ratio1.toString().equals(goodsid.getPsRate())) {
                            hxOrderPutDetailedParam.setUnitType("配送单位");
                        } else if (ratio1.toString().equals(goodsid.getKcRate())) {
                            hxOrderPutDetailedParam.setUnitType("库存单位");
                        }
                        if (ToolUtil.isNotEmpty(memo.toString()) && !memo.toString().equals("null")) {
                            hxOrderPutDetailedParam.setNotes(memo.toString());

                        }

                        if (ToolUtil.isNotEmpty(fid) && !fid.equals("null")) {//单据号
                            // 校验是否已经添加过
                            Integer count = hxOrderPutDetailedService.lambdaQuery()
                                    .eq(HxOrderPutDetailed::getOrderPutNumber, fid)
                                    .count();
                            if (count == detailsArray.length()) {
                                break; // 如果数据库中已存在该订单号，则跳过当前循环
                            }
                        }
                        hxOrderPutDetailedList.add(hxOrderPutDetailedParam);
                    }

                }

                Object fid = ((JSONObject) data).get("fid");// 单据号
                Object handleBy = ((JSONObject) data).get("handle_by");// 处理人
                Object handleMemo = ((JSONObject) data).get("handle_memo");// 处理备注
                Object handleTime = ((JSONObject) data).get("handle_time");// 处理时间
                Object inOrderFid = ((JSONObject) data).get("in_order_fid");// 调入单号
                Object inStoreId = ((JSONObject) data).get("in_store_id");//调往门店id
                Object inStoreName = ((JSONObject) data).get("in_store_name");// 调往门店名称
                Object inStorehouseId = ((JSONObject) data).get("in_storehouse_id");//调入仓库id
                Object inStorehouseName = ((JSONObject) data).get("in_storehouse_name");// 调入仓库名称
                Object itemCount = ((JSONObject) data).get("item_count");// 商品数
                String memo = ((JSONObject) data).get("memo").toString();// 备注

                String cleanMemo2 = EmojiTransferUtil.emojiEncode(memo);


                Object money = ((JSONObject) data).get("money");// 金额
                Object outOrderFid = ((JSONObject) data).get("out_order_fid");// 调出单号
                Object reason = ((JSONObject) data).get("reason");// 联系方式
                Object state = ((JSONObject) data).get("state");// 状态：INIT(初始化),AUDIT(审核),HANDLE(处理通过),HANDLE_REFUSE(处理拒绝),APPROVE(批复通过),APPROVE_REFUSE(批复拒绝),可用值:APPROVE,APPROVE_REFUSE,AUDIT,HANDLE,HANDLE_REFUSE,INIT
                Object storeId = ((JSONObject) data).get("store_id");// 申请门店id
                Object storeName = ((JSONObject) data).get("store_name");// 门店名称
                Object storehouseId = ((JSONObject) data).get("storehouse_id");// 出货仓库id
                Object storehouseName = ((JSONObject) data).get("storehouse_name");// 仓库名称
                Object type = ((JSONObject) data).get("type");// 申请类型
                Object updateBy = ((JSONObject) data).get("update_by");// 最后修改人
                Object updateTime = ((JSONObject) data).get("update_time");// 最后修改时间


                if (ToolUtil.isNotEmpty(fid) && !fid.equals("null")) {//单据号
                    // 校验是否已经添加过
                    Integer count = hxOrderPutService.lambdaQuery()
                            .eq(HxOrderPut::getOrderPutNumber, fid)
                            .ne(HxOrderPut::getOrderState, "作废")
                            .count();
                    if (count > 0) {
                        continue; // 如果数据库中已存在该订单号，则跳过当前循环
                    }
                }
                Date date = new Date();

                hxOrderPutParam.setOrderPutNumber(String.valueOf(fid));

                if (ToolUtil.isNotEmpty(auditTime.toString()) && !auditTime.toString().equals("null")) {
                    hxOrderPutParam.setYuyueTime(auditTime.toString());// 预约时间
                } else {
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String dateString = dateFormat.format(date);
                    hxOrderPutParam.setYuyueTime(dateString);// 预约时间
                }

                BasicPutgoods basicPutgoods = basicPutgoodsService.lambdaQuery()
                        .eq(BasicPutgoods::getPutgoodsCustomerId, r.getId())
                        .eq(BasicPutgoods::getXlbClientId, storeId.toString())
                        .eq(BasicPutgoods::getPutgoodsName, storeName.toString())
                        .last("limit 1")
                        .one();

//
//				BasicWarehouse basicWarehouse = basicWarehouseService.lambdaQuery()
//						.eq(BasicWarehouse::getWarehouseXlbId,storehouseId.toString())
//						.one();

                if (basicPutgoods == null) {
                    BasicPutgoods bpgp3 = new BasicPutgoods();
                    bpgp3.setPutgoodsCustomerId(r.getId());
                    bpgp3.setPutgoodsOperateName(r.getCustomerName());
                    bpgp3.setPutgoodsName(storeName.toString());//单位名称
                    bpgp3.setPutgoodsAddress(storeName.toString());//地点 为单位名称
                    bpgp3.setXlbClientId(storeId.toString());
                    bpgp3.setUnitType("门店");
                    bpgp3.setDictId(0l);
                    bpgp3.setDeliverId(user.getDeliverId());
                    bpgp3.setDeptId(user.getDeptId());
                    basicPutgoodsService.save(bpgp3);
                    BasicAddress bap3 = new BasicAddress();

                    bap3.setPutgoodsId(Long.parseLong(bpgp3.getId().toString()));
                    bap3.setPutgoodsName(storeName.toString());//单位名称
                    bap3.setAddress(storeName.toString());//地点 为单位名称
                    bap3.setLongitude("0");
                    bap3.setLatitude("0");
                    bap3.setSwitchWl("1");
                    bap3.setSwitchBj("1500");//提货围栏半径 默认100米
                    bap3.setSwitchBj2("2000");//收货围栏半径 默认100米
                    basicAddressService.save(bap3);

                    hxOrderPutParam.setSetUnitId((long) bpgp3.getId());// 发货客户id
                } else {
                    hxOrderPutParam.setSetUnitId((long) basicPutgoods.getId());// 发货客户id
                }

//				hxOrderPutParam.setGetUnit(storeName.toString());// 收货门店名称
//				hxOrderPutParam.setGetUnitId((long) basicPutgoods.getId());//收货门店id
                hxOrderPutParam.setSetUnit(storeName.toString());//发货客户

                hxOrderPutParam.setGetWarehouse(w.getWarehouseName());// 收货仓库名称

                hxOrderPutParam.setGetWarehouseId((long) w.getId());//收货仓库id
//				hxOrderPutParam.setNotes(memo.toString());// 备注

                hxOrderPutParam.setNotes(cleanMemo2); // 转换备注

                hxOrderPutParam.setGoodsNum(itemCount.toString());//商品数
                hxOrderPutParam.setCreateTime(date);// 创建时间

                hxOrderPutParam.setOrderState("待处理");
                if (type.toString().equals("RETURN")) {
                    hxOrderPutParam.setOrderType("门店退货");
                }
                if (type.toString().equals("DELIVERY")) {
                    hxOrderPutParam.setOrderType("直调申请");
                }
                if (type.toString().equals("TRANSFER")) {
                    hxOrderPutParam.setOrderType("门店调拨");
                }
                hxOrderPutParam.setCreateUserName(user.getName());
                hxOrderPutParam.setXlbOrderId(String.valueOf(fid));
                hxOrderPutParam.setDeptId(user.getDeptId());
                hxOrderPutParam.setDeliverId(user.getDeliverId());
                hxOrderPutParam.setCustomerId((long) r.getId());
                hxOrderPutParam.setCustomerName(r.getCustomerName());
                hxOrderPutList.add(hxOrderPutParam);

            }

            this.hxOrderPutDetailedService.saveBatch(hxOrderPutDetailedList);

            this.hxOrderPutService.saveBatch(hxOrderPutList);
        }
        return ResponseData.success();

    }


    /**
     * 跳转到查询页面
     *
     * @author zhucx
     * @Date 2023-08-05
     */
    @RequestMapping("toReturnQuery")
    public String toReturnQuery(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId, deliverId, user.getOperateId()));
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/returnQuery.html";
    }

    /**
     * 跳转到确认页面
     *
     * @author zhucx
     * @Date 2023-08-05
     */
    @RequestMapping("toConfirm")
    public String toConfirm(Model model) {
        return PREFIX + "/confirm.html";
    }

    /**
     * 批量提交
     */
    @RequestMapping("/submission")
    @ResponseBody
    public ResponseData submission(@RequestParam("ids") Long[] ids) {
        ResponseData data = new ResponseData();
        lock.lock();//获取锁
        try {
            //批量生成入库单 ，托盘
            for (Long id : ids) {
                //判断明细是否添加了
                HxOrderPut hxOrderPut = hxOrderPutService.getById(id);
                if ("待提交".equals(hxOrderPut.getOrderState()) || "撤回".equals(hxOrderPut.getOrderState())) {
                    QueryWrapper <HxOrderPutDetailed> queryWrapper = new QueryWrapper <HxOrderPutDetailed>();
                    queryWrapper.eq("order_put_number", hxOrderPut.getOrderPutNumber());
                    int count = hxOrderPutDetailedService.count(queryWrapper);
                    if (count > 0) {
                        hxStoragePutDetailedService.submissionOrder(hxOrderPut);
                    } else {
                        data.setSuccess(false);
                        data.setMessage("请先添加商品明细，单号：" + hxOrderPut.getOrderPutNumber());
                        return data;
                    }
                } else if ("待处理".equals(hxOrderPut.getOrderState())) {
                    data.setSuccess(false);
                    data.setMessage("请先处理订单，单号：" + hxOrderPut.getOrderPutNumber());
                    return data;
                }else if ("处理拒绝".equals(hxOrderPut.getOrderState())) {
                    data.setSuccess(false);
                    data.setMessage("订单已拒绝不可提交，单号：" + hxOrderPut.getOrderPutNumber());
                    return data;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//释放锁
        }
        return ResponseData.success();
    }


    /**
     * 导入页面
     */
    @RequestMapping("/toimportExcel")
    public String toimportExcel(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId, deliverId, user.getOperateId()));

        //查询可选择仓库
        model.addAttribute("wlist", basicWarehouseService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/import.html";
    }

    /**
     * 上传excel
     */
    @RequestMapping(value = "/importExceNewmethodl", method = {RequestMethod.POST})
    @ResponseBody
    public ResponseData importExceNewmethodl(@RequestPart("file") MultipartFile file, HxOrderPutParam hxOrderPutParam) {
        ResponseData data = new ResponseData();
        if (hxOrderPutParam.getGetWarehouseId() == null || hxOrderPutParam.getCustomerId() == null) {
            data.setSuccess(false);
            data.setMessage("请填写订单基本信息!");
            return data;
        }
        lock.lock();//获取锁
        try {
            data = hxOrderPutService.getExceldata(file, hxOrderPutParam, data);//处理导入数据
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//释放锁
        }
        return data;
    }

    /**
     * 下载入库订单模板
     *
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadExcelTemplate")
    public void downloadExcelTemplate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = "assets/excel/hxorderPut.xlsx";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("零售入库订单模板" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入页面
     */
    @RequestMapping("/toimportKhExcel")
    public String toimportKhExcel(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId, deliverId, user.getOperateId()));

        //查询可选择仓库
        model.addAttribute("wlist", basicWarehouseService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/importKh.html";
    }

    /**
     * 上传excel
     */
    @RequestMapping(value = "/importKhExcel", method = {RequestMethod.POST})
    @ResponseBody
    public ResponseData importKhExcel(@RequestPart("file") MultipartFile file, HxOrderPutParam hxOrderPutParam) {
        ResponseData data = new ResponseData();
        if (hxOrderPutParam.getGetWarehouseId() == null || hxOrderPutParam.getCustomerId() == null) {
            data.setSuccess(false);
            data.setMessage("请填写订单基本信息!");
            return data;
        }
        lock.lock();//获取锁
        try {
            data = hxOrderPutService.getExceldataKh(file, hxOrderPutParam, data);//处理导入数据
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//释放锁
        }
        return data;
    }

    /**
     * 下载入库订单模板
     *
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadKhExcelTemplate")
    public void downloadKhExcelTemplate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = "assets/excel/khOrderIn.xlsx";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("多点入库订单模板" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 批量打印入库订单  页面
     */
    @RequestMapping("print")
    public String print() {
        return PREFIX + "/print.html";
    }

    /**
     * 批量打印退货订单  页面
     */
    @RequestMapping("return_print")
    public String return_print() {
        return PREFIX + "/return_print.html";
    }

    /**
     * 打印查询
     * 入库订单信息
     */
    @ResponseBody
    @RequestMapping("/getPrintOrderPut")
    public HxOrderPutResult getPrintOrderPut(HxOrderPutParam hxOrderPutParam) {
        User user = userService.getcurrentUser();
        HxOrderPutResult res = hxOrderPutService.getPrintOrderPut(hxOrderPutParam);
        res.setPrintName(user.getName());
        return res;
    }

    /**
     * 打印查询
     * 入库单明细信息
     */
    @ResponseBody
    @RequestMapping("/getPrintOrderPutDetailed")
    public List <HxOrderPutDetailedResult> getPrintOrderPutDetailed(String orderPutNumber) {
        HxOrderPutDetailedParam bxOrderPutDetailedParam = new HxOrderPutDetailedParam();
        bxOrderPutDetailedParam.setOrderPutNumber(orderPutNumber);

        List <HxOrderPutDetailedResult> list = hxOrderPutDetailedService.findListBySpec2(bxOrderPutDetailedParam);
        List <HxOrderPutDetailedResult> list2 = new ArrayList <HxOrderPutDetailedResult>();
        List <HxOrderPutDetailedResult> list3 = new ArrayList <HxOrderPutDetailedResult>();
        for (int i = 0; i < list.size(); i++) {
            list3.add(list.get(i));
            if (list3.size() == 40) {
                HxOrderPutDetailedResult r = new HxOrderPutDetailedResult();
                r.setList(list3);
                list2.add(r);
                list3 = new ArrayList <HxOrderPutDetailedResult>();
            }
        }
        if (list3.size() > 0) {
            HxOrderPutDetailedResult r = new HxOrderPutDetailedResult();
            r.setList(list3);
            list2.add(r);
        }
        return list2;
    }

    /**
     * 新增页面
     *
     * @author zhucx
     * @Date 2023-08-05
     */
    @RequestMapping("/add")
    public String add(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId, deliverId, user.getOperateId()));
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/hxOrderPut_add.html";
    }

    /**
     * 新增页面
     *
     * @author zhucx
     * @Date 2023-08-05
     */
    @RequestMapping("/return_add")
    public String return_add(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId, deliverId, user.getOperateId()));
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/hxOrderPut_return_add.html";
    }

    /**
     * 编辑页面
     *
     * @author zhucx
     * @Date 2023-08-05
     */
    @RequestMapping("/edit")
    public String edit(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId, deliverId, user.getOperateId()));
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/hxOrderPut_edit.html";
    }

    /**
     * 编辑页面
     *
     * @author zhucx
     * @Date 2023-08-05
     */
    @RequestMapping("/return_edit")
    public String return_edit(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId, deliverId, user.getOperateId()));
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/hxOrderPut_return_edit.html";
    }

    @Autowired
    private DeptService deptService;

    /**
     * 获取所属项目单号前缀
     *
     * @param user
     * @return
     */
    public String getOperateIdOrderPrefix(User user) {
        if (user.getOperateId() != null) {
            Dept dept = new Dept();
            dept.setOperateId(user.getOperateId());
            Dept resdept = deptService.findBySpec(dept);
            if (resdept != null) {
                if (ToolUtil.isNotEmpty(resdept.getOrderPrefix())) {
                    return resdept.getOrderPrefix();
                } else {
                    return user.getAccount().substring(0, 3);
                }
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 新增接口
     *
     * @author zhucx
     * @Date 2023-08-05
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(HxOrderPutParam hxOrderPutParam) {
        User user = userService.getcurrentUser();
        String trayCode = getOperateIdOrderPrefix(user);
        if (ToolUtil.isNotEmpty(hxOrderPutParam.getOrderPutNumber())) {
            //校验客户单号 是否存在
            if (this.hxOrderPutService.checkCustomerOrder(hxOrderPutParam.getOrderPutNumber())) {
                return ResponseData.error("单号已存在");
            }
        } else {
            hxOrderPutParam.setOrderPutNumber(trayCode + "RK" + DateUtil.getDatesBch() + DateUtil.getRandomNumber());
        }
        Object WarehouseId = hxOrderPutParam.getGetWarehouseId();
        if (WarehouseId != null) {
            BasicWarehouse bawBasicWarehouse = basicWarehouseService.getById(Integer.parseInt(WarehouseId.toString()));
            hxOrderPutParam.setGetWarehouse(bawBasicWarehouse.getWarehouseName());//set 仓库名称
        }
        Object CustomerId = hxOrderPutParam.getCustomerId();
        if (CustomerId != null) {
            BasicCustomer basicCustomer = basicCustomerService.getById(Integer.parseInt(CustomerId.toString()));
            hxOrderPutParam.setCustomerName(basicCustomer.getCustomerName());//set 客户名称
        }
        hxOrderPutParam.setDeptId(user.getDeptId());
        hxOrderPutParam.setDeliverId(user.getDeliverId());
        hxOrderPutParam.setOrderState("待提交");//set 单据状态
        hxOrderPutParam.setCreateUserName(user.getName());//set 制单用户名称
        this.hxOrderPutService.add(hxOrderPutParam);
        return ResponseData.success();
    }

    /**
     * 新增接口
     *
     * @author zhucx
     * @Date 2023-08-05
     */
    @RequestMapping("/return_addItem")
    @ResponseBody
    public ResponseData return_addItem(HxOrderPutParam hxOrderPutParam) {
        User user = userService.getcurrentUser();
        String trayCode = getOperateIdOrderPrefix(user);
        if (ToolUtil.isNotEmpty(hxOrderPutParam.getOrderPutNumber())) {
            //校验客户单号 是否存在
            if (this.hxOrderPutService.checkCustomerOrder(hxOrderPutParam.getOrderPutNumber())) {
                return ResponseData.error("单号已存在");
            }
        } else {
            hxOrderPutParam.setOrderPutNumber(trayCode + "RK" + DateUtil.getDatesBch() + DateUtil.getRandomNumber());
        }
        Object WarehouseId = hxOrderPutParam.getGetWarehouseId();
        if (WarehouseId != null) {
            BasicWarehouse bawBasicWarehouse = basicWarehouseService.getById(Integer.parseInt(WarehouseId.toString()));
            hxOrderPutParam.setGetWarehouse(bawBasicWarehouse.getWarehouseName());//set 仓库名称
        }
        Object CustomerId = hxOrderPutParam.getCustomerId();
        if (CustomerId != null) {
            BasicCustomer basicCustomer = basicCustomerService.getById(Integer.parseInt(CustomerId.toString()));
            hxOrderPutParam.setCustomerName(basicCustomer.getCustomerName());//set 客户名称
        }
        hxOrderPutParam.setDeptId(user.getDeptId());
        hxOrderPutParam.setDeliverId(user.getDeliverId());
        hxOrderPutParam.setOrderState("待提交");//set 单据状态
        hxOrderPutParam.setCreateUserName(user.getName());//set 制单用户名称
        this.hxOrderPutService.add(hxOrderPutParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author zhucx
     * @Date 2023-08-05
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(HxOrderPutParam hxOrderPutParam) {
        //校验客户单号 是否存在
        HxOrderPut hxOrderPut = this.hxOrderPutService.getById(hxOrderPutParam.getId());
        if (!hxOrderPut.getOrderPutNumber().equals(hxOrderPutParam.getOrderPutNumber())) {
            if (this.hxOrderPutService.checkCustomerOrder(hxOrderPutParam.getOrderPutNumber())) {
                return ResponseData.error("单号已存在");
            }
        }
        Object WarehouseId = hxOrderPutParam.getGetWarehouseId();
        if (WarehouseId != null) {
            BasicWarehouse bawBasicWarehouse = basicWarehouseService.getById(Integer.parseInt(WarehouseId.toString()));
            hxOrderPutParam.setGetWarehouse(bawBasicWarehouse.getWarehouseName());//set 仓库名称
        }
        Object CustomerId = hxOrderPutParam.getCustomerId();
        if (CustomerId != null) {
            BasicCustomer basicCustomer = basicCustomerService.getById(Integer.parseInt(CustomerId.toString()));
            hxOrderPutParam.setCustomerName(basicCustomer.getCustomerName());//set 客户名称
        }
        this.hxOrderPutService.update(hxOrderPutParam);
        return ResponseData.success();
    }

    /**
     * 批量作废
     */
    @RequestMapping("/tovoid")
    @ResponseBody
    public ResponseData tovoid(@RequestParam("ids") Long[] ids) {
        for (Long id : ids) {
            HxOrderPut hxOrderPut = this.hxOrderPutService.getById(id);
            if (hxOrderPut.getOrderState().equals("撤回") || hxOrderPut.getOrderState().equals("待提交") || hxOrderPut.getOrderState().equals("待处理")) {
                HxOrderPutParam param = new HxOrderPutParam();
                param.setOrderState("作废");
                param.setId(Integer.parseInt(id.toString()));
                hxOrderPutService.update(param);
            }
        }
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author zhucx
     * @Date 2023-08-05
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(HxOrderPutParam hxOrderPutParam) {
        this.hxOrderPutService.delete(hxOrderPutParam);
        return ResponseData.success();
    }

    /**
     * 批量删除
     */
    @RequestMapping("/btnDelete")
    @ResponseBody
    public ResponseData btnDelete(Long ids[]) {
        for (Long id : ids) {
            HxOrderPut hxOrderPut = hxOrderPutService.getById(id);
            if (hxOrderPut.getOrderState().equals("作废")) {
                HxOrderPutDetailedParam detailedParam = new HxOrderPutDetailedParam();
                detailedParam.setOrderPutNumber(hxOrderPut.getOrderPutNumber());
                hxOrderPutDetailedService.deleteBySpec(detailedParam);

                HxOrderPutParam hxOrderPutParam = new HxOrderPutParam();
                hxOrderPutParam.setId(hxOrderPut.getId());
                this.hxOrderPutService.delete(hxOrderPutParam);
            } else {
                return ResponseData.error("只可删除作废订单");
            }
        }
        return ResponseData.success();
    }

    /**
     * 撤回
     */
    @RequestMapping("/revoke")
    @ResponseBody
    @Permission
    public ResponseData revoke(HxOrderPutParam hxOrderPutParam) {
        ResponseData data = new ResponseData();
        HxOrderPut hxOrderPut = hxOrderPutService.getById(hxOrderPutParam.getId());
        if ("收货中".equals(hxOrderPut.getOrderState())) {
            data = hxOrderPutService.revoke(hxOrderPut, data);
        } else {
            data.setMessage("已开始收货无法撤回");
            data.setSuccess(false);
        }
        return data;
    }

    /**
     * 查看详情接口
     *
     * @author zhucx
     * @Date 2023-08-05
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(HxOrderPutParam hxOrderPutParam) {
        HxOrderPut detail = this.hxOrderPutService.getById(hxOrderPutParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author zhucx
     * @Date 2023-08-05
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(HxOrderPutParam hxOrderPutParam, String condition, String startTime, String endTime) {
        User user = userService.getcurrentUser();
        hxOrderPutParam.setDeptId(user.getDeptId());
        if (ToolUtil.isEmpty(hxOrderPutParam.getTimeType())) {
            hxOrderPutParam.setTimeType("cj");
        }
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxOrderPutParam.setTimeInterval("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            hxOrderPutParam.setTimeInterval("'" + DateUtil.getDate() + "' and '" + DateUtil.getDate() + "'");
        }
        return this.hxOrderPutService.findPageBySpec(hxOrderPutParam, condition, user.getOperateId());
    }

    /**
     * 查询列表
     *
     * @author zhucx
     * @Date 2023-08-05
     */
    @ResponseBody
    @RequestMapping("/querylist")
    public LayuiPageInfo querylist(HxOrderPutParam hxOrderPutParam, String condition, String startTime, String endTime) {
        User user = userService.getcurrentUser();
        hxOrderPutParam.setDeptId(user.getDeptId());
        if (ToolUtil.isEmpty(hxOrderPutParam.getTimeType())) {
            hxOrderPutParam.setTimeType("cj");
        }
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxOrderPutParam.setTimeInterval("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            hxOrderPutParam.setTimeInterval("'" + DateUtil.getDate() + "' and '" + DateUtil.getDate() + "'");
        }
        return this.hxOrderPutService.findqueryPageBySpec(hxOrderPutParam, condition, user.getOperateId());
    }

    /**
     * 查询列表
     *
     * @author zhucx
     * @Date 2023-08-05
     */
    @ResponseBody
    @RequestMapping("/returnlist")
    public LayuiPageInfo returnlist(HxOrderPutParam hxOrderPutParam, String condition, String startTime, String endTime) {
        User user = userService.getcurrentUser();
        hxOrderPutParam.setDeptId(user.getDeptId());
        if (ToolUtil.isEmpty(hxOrderPutParam.getTimeType())) {
            hxOrderPutParam.setTimeType("cj");
        }
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxOrderPutParam.setTimeInterval("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            hxOrderPutParam.setTimeInterval("'" + DateUtil.getDate() + "' and '" + DateUtil.getDate() + "'");
        }
        return this.hxOrderPutService.findreturnPageBySpec(hxOrderPutParam, condition, user.getOperateId());
    }

    /**
     * 查询列表
     *
     * @author zhucx
     * @Date 2023-08-05
     */
    @ResponseBody
    @RequestMapping("/returnQuerylist")
    public LayuiPageInfo returnQuerylist(HxOrderPutParam hxOrderPutParam, String condition, String startTime, String endTime) {
        User user = userService.getcurrentUser();
        hxOrderPutParam.setDeptId(user.getDeptId());
        if (ToolUtil.isEmpty(hxOrderPutParam.getTimeType())) {
            hxOrderPutParam.setTimeType("cj");
        }
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxOrderPutParam.setTimeInterval("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            hxOrderPutParam.setTimeInterval("'" + DateUtil.getDate() + "' and '" + DateUtil.getDate() + "'");
        }
        return this.hxOrderPutService.findreturnQueryPageBySpec(hxOrderPutParam, condition, user.getOperateId());
    }

    /**
     * 合计
     */
    @ResponseBody
    @RequestMapping("/count")
    public ResponseData count(HxOrderPutParam hxOrderPutParam, String condition, String startTime, String endTime) {
        User user = userService.getcurrentUser();
        hxOrderPutParam.setDeptId(user.getDeptId());
        hxOrderPutParam.setDeliverId(user.getDeliverId());
        if (ToolUtil.isEmpty(hxOrderPutParam.getTimeType())) {
            hxOrderPutParam.setTimeType("cj");
        }
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxOrderPutParam.setTimeInterval("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            hxOrderPutParam.setTimeInterval("'" + DateUtil.getDate() + "' and '" + DateUtil.getDate() + "'");
        }
        return ResponseData.success(this.hxOrderPutService.count(hxOrderPutParam, condition, user.getOperateId()));

    }

    @ResponseBody
    @RequestMapping("/count1")
    public ResponseData count1(HxOrderPutParam hxOrderPutParam, String condition, String startTime, String endTime) {
        User user = userService.getcurrentUser();
        hxOrderPutParam.setDeptId(user.getDeptId());
        hxOrderPutParam.setDeliverId(user.getDeliverId());
        if (ToolUtil.isEmpty(hxOrderPutParam.getTimeType())) {
            hxOrderPutParam.setTimeType("cj");
        }
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxOrderPutParam.setTimeInterval("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            hxOrderPutParam.setTimeInterval("'" + DateUtil.getDate() + "' and '" + DateUtil.getDate() + "'");
        }
        return ResponseData.success(this.hxOrderPutService.count1(hxOrderPutParam, condition, user.getOperateId()));

    }

    @ResponseBody
    @RequestMapping("/count2")
    public ResponseData count2(HxOrderPutParam hxOrderPutParam, String condition, String startTime, String endTime) {
        User user = userService.getcurrentUser();
        hxOrderPutParam.setDeptId(user.getDeptId());
        hxOrderPutParam.setDeliverId(user.getDeliverId());
        if (ToolUtil.isEmpty(hxOrderPutParam.getTimeType())) {
            hxOrderPutParam.setTimeType("cj");
        }
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxOrderPutParam.setTimeInterval("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            hxOrderPutParam.setTimeInterval("'" + DateUtil.getDate() + "' and '" + DateUtil.getDate() + "'");
        }
        return ResponseData.success(this.hxOrderPutService.count2(hxOrderPutParam, condition, user.getOperateId()));

    }
}


